Monday, 31 January 2022

FastAPI: response_model_include and response_model_exclude: Exclude and include fields from response model

response_model_include and response_model_exclude path operation decorator parameters are used to specify which fields are included/excluded from the response model.

 

Example 1: using response_model_include

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

 

Example 2: Using response_model_exclude

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

 

Find the below working application.

 

responseModelExcludeInclude.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-ex1/{empId}", response_model = Employee, response_model_include ={'name', 'country'})
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))

@app.get("/emps/by-id-ex2/{empId}", response_model = Employee, response_model_exclude={'age','tax'})
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 responseModelExcludeInclude:app --reload'.

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

 

Open the url ‘http://localhost:8000/docs’ in browser, you will see swagger documentation.

 


 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment