FastAPI use Pydnatic models to declare a request body.
Step 1: Import BaseModel from pydantic.
from pydantic import BaseModel
Step 2: Define a class by extending BaseModel class.
class Employee(BaseModel):
name: str
age: int
Step 3: Define a fucnction to create an employee.
@app.post("/emps")
def createEmployee(emp: Employee):
noOfEmps = len(emps)
newId = noOfEmps + 1
emps[newId] = emp
return {"id" : newId, "name" : emp.name, "age": emp.age}
Find the below working application.
main.py
from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
app = FastAPI()
class Employee(BaseModel):
name: str
age: int
# employees information
emps = {
1 : {
"name" : "Krishna",
"age": 32
},
2 : {
"name" : "Ram",
"age": 33
}
}
# Create an endpoint
@app.get("/")
def home():
return {"name" : "Hello World app", "version": "2.0.0"}
# Employees REST APIs
@app.get("/emps")
def allEmployees():
return emps
@app.get("/emps/by-id/{empId}")
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
if(empId in emps):
return emps[empId]
else:
raise Exception("Employee not exist with given id " + str(empId))
@app.get("/emps/by-name")
def empByName(name: Optional[str] = None):
if name == None:
return {"message" : "no input provided"}
for empId in emps:
if emps[empId]["name"] == name:
return emps[empId]
return {"message" : "Not found"}
@app.post("/emps")
def createEmployee(emp: Employee):
noOfEmps = len(emps)
newId = noOfEmps + 1
emps[newId] = emp
return {"id" : newId, "name" : emp.name, "age": emp.age}
Run the application by executing the command ‘uvicorn main:app --reload’.
Open the url ‘http://127.0.0.1:8000/docs’ in browser.
Work with the API 'POST /emps'
No comments:
Post a Comment