English 中文(简体)
FastAPI - Response Model
  • 时间:2024-11-03

FastAPI - Response Model


Previous Page Next Page  

An operation function returns A JSON response to the cpent. The response can be in the form of Python primary types, i.e., numbers, string, pst or dict, etc. It can also be in the form of a Pydantic model. For a function to return a model object, the operation decorator should declare a respone_model parameter.

With the help of response_model, FastAPI Converts the output data to a structure of a model class. It vapdates the data, adds a JSON Schema for the response, in the OpenAPI path operation.

One of the important advantages of response_model parameter is that we can format the output by selecting the fields from the model to cast the response to an output model.

Example

In the following example, the POST operation decorator receives the request body in the form of an object of the student class (a subclass of BaseModel). As one of the fields in this class, i.e. marks (a pst of marks) is not needed in the response, we define another model called percent and use it as the response_model parameter.


from typing import List
from fastapi import FastAPI
from pydantic import BaseModel, Field
app = FastAPI()
class student(BaseModel):
   id: int
   name :str = Field(None, title="name of student", max_length=10)
   marks: List[int] = []
   percent_marks: float
class percent(BaseModel):
   id:int
   name :str = Field(None, title="name of student", max_length=10)
   percent_marks: float
@app.post("/marks", response_model=percent)
async def get_percent(s1:student):
   s1.percent_marks=sum(s1.marks)/2
   return s1

If we check the Swagger documentation, it shows that the "/marks" route gets an object of student class as the request body. Populate the attributes with appropriate values and execute the get_percent() function.

FastAPI Response Model

The server response is cast to the percent class as it has been used as the response_model.

FastAPI Response Model Advertisements