🍈Unit 16: Response Model - Return Type
Introduction
Response Model and Response Type are crucial concepts for defining the structure of the responses your API will send to the client.
Response Model
The "Response Model" in FastAPI is used to:
Define the data structure of the response sent to the client.
Automatically convert the output data to this structure.
Validate the data before sending it to the client.
Limit the data that you send to the client, allowing you to hide certain data that the client does not need to receive.
You define a response model by creating a Pydantic model that describes the structure of the response. Then, you specify this model as the response_model
argument in your path operation function (like @app.get()
or @app.post()
).
In this example, the Item
model is used as the response model for the create_item
function. This means FastAPI will:
Ensure the response matches the
Item
model structure.Convert the output to JSON format using the model's definition.
Validate the response data.
Document the API with the model.
Let's extend the program by defining a new class, named ItemV2
(line 12) where we exclude the description
attribute from the original Item
. The create_item
(line 22) receives an item having 4 attributes since it is based on the Item
class, and returns an item having 3 attributes based on ItemV2
class.
You can open the API Docs (http://127.0.0.1:8000/docs/) and view the Schemas
of Item
and ItemV2
, as shown in Fig. 1.
Return Type
The "Return Type" of a path operation function is inferred from the Python type hints. FastAPI uses these type hints to perform data conversion (serialization and deserialization), validation, and documentation.
For example, if you have a path operation function that returns an instance of a Pydantic model, FastAPI will serialize this model to JSON using the model's schema. If you use standard Python types (like dict
, list
, str
, int
), FastAPI will directly convert these to JSON.
You can return any object that can be converted to JSON, including Pydantic models, dict
, list
, tuple
, and standard Python types. FastAPI will handle the conversion and ensure the response is in the correct format.
The usage of response models and return types in FastAPI allows for flexible and efficient API design. You can define the structure and constraints of your data using Pydantic models, and FastAPI will handle the serialization, validation, and documentation.
Last updated