Monday, 13 December 2021

FastAPI: Declare Response model object

FastAPI allows you to declare the model used for the response with the parameter response_model in any of the http operations like get, post, put etc.,

 

Example

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

 

In the above example, I set Employee as reponse type to the method empById. Find the below working application.

 

responseModel1.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

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

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

@app.get("/emps/by-id/{empId}", response_model = Employee)
def empById(empId: int = Path(None, description = "Enter valid employee id", gt = 0, lt = 3)):
    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 responseModel1:app --reload’.

 

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

  Open the url ‘http://localhost:8000/docs’ in browser and expand the api 'GET /emps/by-id/{empId}', you will see the response model in Responses section against 200 status code.

 


 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment