Monday 15 November 2021

FastAPI: PUT request example

Step 1: Import Optional and BaseModel classes

from typing import Optional
from pydantic import BaseModel

Step 2: Define a model class to map PUT request payload.

class EmployeeUpdateDto(BaseModel):
    name: Optional[str]
    age : Optional[int]

Step 3: Define a method that handle PUT call.

@app.put("/emps/by-id/{empId}")
def updateEmployee(empId : int, emp: EmployeeUpdateDto):
    if(empId not in emps):
        return {"message" : "Not found"}
    
    persistedEmp = emps[empId]

    if(emp.name != None):
        persistedEmp["name"] = emp.name
    
    if(emp.age != None):
        persistedEmp["age"] = emp.age

    return {"id" : empId, "name" : persistedEmp["name"], "age": persistedEmp["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

class EmployeeUpdateDto(BaseModel):
    name: Optional[str]
    age : Optional[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}

@app.put("/emps/by-id/{empId}")
def updateEmployee(empId : int, emp: EmployeeUpdateDto):
    if(empId not in emps):
        return {"message" : "Not found"}
    
    persistedEmp = emps[empId]

    if(emp.name != None):
        persistedEmp["name"] = emp.name
    
    if(emp.age != None):
        persistedEmp["age"] = emp.age

    return {"id" : empId, "name" : persistedEmp["name"], "age": persistedEmp["age"]}

Run the application by executing the command ‘uvicorn main:app --reload’.

$uvicorn main:app --reload
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [63314] using statreload
INFO:     Started server process [63316]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Open the url ‘http://127.0.0.1:8000/docs’ in browser and experiment with the API 'PUT /emps/by-id/{empId}'.







 

 Previous                                                    Next                                                    Home

No comments:

Post a Comment