Monday, 29 November 2021

FastAPI: Mix path, query and request body in one request

You can mix path, query and request body in one request.

 

Example

@app.put("/emps/by-id/{empId}")
def updateEmployee(empId : int, emp: EmployeeUpdateDto, gender: Optional[str] = None)

 

In the above example,

a.   empId is the path parameter

b.   emp is the request payload

c.    gender is a query parameter

 

Find the below working application.

 

mixParams.py

from fastapi import FastAPI, Path, Query
from pydantic import BaseModel
from typing import Optional

app = FastAPI()

# employees information
emps = {
    1 : {
        "name" : "Krishna",
        "age": 32,
        "gender" : 'M'
    },
    2 : {
        "name" : "Ram",
        "age": 33,
        "gender" : 'F'
    },
    3 : {
        "name" : "Bomma",
        "age": 38,
        "gender" : 'M'
    }
}

class EmployeeUpdateDto(BaseModel):
    name: str
    age : int

@app.get("/emps")
def allEmployees():
    return emps

@app.put("/emps/by-id/{empId}")
def updateEmployee(empId : int, emp: EmployeeUpdateDto, gender: Optional[str] = None):
    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

    persistedEmp["gender"] = gender

    if(gender == None):
        persistedEmp["gender"] = 'M'
    
    return {
        "id" : empId, 
        "name" : persistedEmp["name"], 
        "age": persistedEmp["age"], 
        "gender" : persistedEmp["gender"]
        }

 

Open terminal and execute the command ‘uvicorn mixParams:app --reload’.

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

 

Open the url ‘http://127.0.0.1:8000/docs’ in browser and experiment with swagger documentation.

 


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment