0% found this document useful (0 votes)
3 views4 pages

Building API - MD

The document outlines how to handle various HTTP request methods (GET, POST, PUT, DELETE) using Flask for an API that manages student data. It includes examples of API endpoints for retrieving, creating, updating, and deleting student records, with responses formatted in JSON. Additionally, it addresses the need to convert MongoDB ObjectId to string for serialization in responses.

Uploaded by

Jevon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views4 pages

Building API - MD

The document outlines how to handle various HTTP request methods (GET, POST, PUT, DELETE) using Flask for an API that manages student data. It includes examples of API endpoints for retrieving, creating, updating, and deleting student records, with responses formatted in JSON. Additionally, it addresses the need to convert MongoDB ObjectId to string for serialization in responses.

Uploaded by

Jevon
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Handle Request Methods

I need to have a tool to handle all of the request methods, like Postman or Insomnia

Structure of API
API Endpoint

It is the URL that represents specified resource or function in API

Return Response to Server

from flask import Flask, Response


import json
import os

app = Flask(__name__)

@[Link]("/api/v1.0/studnets", methods = ["GET"])

def students():
student_list = [
{
"name": "Jevon",
"country": "Indonesia",
"skills": ["Coding", "Workout", "Trading"]
},
{
"name": "Alvaro",
"country": "Indonesia",
"skills": ["Trading", "Communicating"]
}
]

return Response([Link](student_list), mimetype="application/json")

Return Response of Full Data from MongoDB

MONGODB_URL = ...
client = [Link](MONGODB_URL)
db = client["thirty_days_of_python"]
...
def students():
data = list([Link]())
## It is said that MongoDB _id is not serializable, cannot encode
ObjectId, so convert it to string first
for item in data:
item["_id"] = str(item["_id"])

return Response([Link](data), mimetype="application/json")

Return Response of Data with Specified Id

## Flask should accept anything in the url <id> and store it in a variable
called id
@[Link]("/api/v1.0/students/<id>", methods = ['GET'])

def single_student(id):

student = [Link].find_one({"_id": ObjectId(id)})

if student:

student["_id"] = str(student["_id"])

return Response([Link](student), mimetype="application/json")

else:

return Response([Link]({"error": "student not found"}),


status=404, mimetype="application/json")

Create Data by POST

@[Link]("/api/v1.0/students", methods = ["POST"])

def create_student():

name = [Link]["name"]

country = [Link]["country"]

city = [Link]["city"]

age = int([Link]["age"])

student = {

"name": name,
"country": country,

"city": city,

"age": age

[Link].insert_one(student)

return

Update Data by PUT

@[Link]("/api/v1.0/students/<id>", methods = ["PUT"])

def update_student(id):

query = {"_id": ObjectId(id)}

name = [Link]["name"]

country = [Link]["country"]

city = [Link]["city"]

age = int([Link]["age"])

student = {

"name": name,

"country": country,

"city": city,

"age": age

[Link].update_one(query, student)

return Response([Link]({"result": "a student has been updated"}))

Delete Data by DELETE


@[Link]("/api/v1.0/students/<id>", methods = ["DELETE"])

def delete_student(id):

[Link].delete_one({"_id": ObjectId(id)})

return Response([Link]({"result": "a student has been deleted"}))

You might also like