This is the 27th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021.
As we learned in the last article, FastAPI allows you to define a data model class to set the request body parameters. FastAPI also allows you to specify the response_model parameter when defining a route. Response_model receives the same type from the data model class of the BaseModel class of the Pydantic module.
Using the Response Model
Define a response model class User as follows:
class User(BaseModel) :
name: str
password: str = '123456'
sex: str = 'male'
age: int
mobile: str
description: str = None
Copy the code
After defining the response model class, when defining the route, the response_model parameter is set in the decorator function as follows:
@app.post("/add", response_model=User)
async def add(user: User) :
return user
Copy the code
Response_model FastAPI automatically validates the response_model and returns an error if the response_model is not the response_model.
Returns the model class specified property
If you have a Pydantic model class that is used in different places, the data returned will be somewhat inconsistent because each place has different requirements. For example, the interface above does not return the password attribute of the User class. This can be handled using the response_model_include and response_model_exclude parameters.
Response_model_include returns the properties specified in the response model; Response_model_exclude excludes attributes from the response model and returns other attributes.
Response_model_include: response_model_include: response_model_include: response_model_include: response_model_include: response_model_include: response_model_include
@app.post("/add", response_model=User, response_model_include=["name"."sex"."age"])
async def add(user: User) :
return user
Copy the code
Define the base class model
In real development, when multiple response models are defined with repeated properties, we can define a base class model that contains the repeated properties of those response model classes, and then we can create subclasses that inherit from the base class model and extend the properties individually.
class UserBase(BaseModel) :
name: str
sex: str = 'male'
age: int
mobile: str
description: str = None
class UserReq(UserBase) :
password: str = "123456"
class UserRes(UserBase) :
create_time: str
@app.post("/add", response_model=UserRes)
async def add(user: UserReq) :
user_dict = user.dict()
user_dict["create_time"] = str(datetime.datetime.now())
res = UserRes(**user_dict)
return res
Copy the code
The Pydantic model has a.dict() method that converts model data to a dictionary, and **user_dict unpackages the dictionary, passing the keys and values of the unpacked user_dict to UserRes as key-value arguments.
In the above code, a UserBase user information base class is defined, and then the request body model class UserReq and response model class UserRes are created respectively. The attributes of UserBase class are shared and extended respectively, which effectively reduces code duplication.
As you can see from this article, the FastAPI response model is very simple to use, and in a real project, the model class is best defined in a separate file for easy use and management.
Original is not easy, if small partners feel helpful, please click a “like” and then go ~
Finally, thank my girlfriend for her tolerance, understanding and support in work and life!