Sunday, 30 January 2022

FastAPI: response_model_exclude_unset: exclude unset values

By setting the decorator parameter response_model_exclude_unset=True, we can exclude unset values in the response model.

 

Example

@app.get("/emps/by-id/{empId}", response_model = Employee, response_model_exclude_unset=True)
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4))

 

Find the below working application.

 

responseModelExcludeUnset.py

 

from fastapi import FastAPI, Path
from typing import Optional
from pydantic import BaseModel
from enum import Enum

app = FastAPI()

class CountryEnum(str, Enum):
    India = "India"
    China = "China"
    Russia = "Russia"

# model classes
class Employee(BaseModel):
    name: str
    age: int
    country: str = 'India'
    tax: float = 30.5

emp1 = Employee(name= "Krishna", age = 32, country = "India", tax = 20)
emp2 = Employee(name= "Ram", age = 42, country = "China", tax = 35)
emp3 = Employee(name= "Sailu", age = 33)

employees = {1 : emp1, 2 : emp2, 3 : emp3}

@app.get("/emps/by-id/{empId}", response_model = Employee, response_model_exclude_unset=True)
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 4)):
    if(empId in employees):
        return employees[empId]
    else:
        raise Exception("Employee not exist with given id " + str(empId))

Open terminal and execute the command 'uvicorn responseModelExcludeUnset:app --reload'.

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

Open the url ‘http://localhost:8000/docs’ in browser and experiment with the api ‘GET /emps/by-id/{empId}’



As you see above snippet, ‘country’ and ‘tax’ are excluded and only ‘name’ and ‘age’ fields are returned for employee id 3.


  

Previous                                                    Next                                                    Home

No comments:

Post a Comment