Customizing response model
FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. Today, we will discuss how to customize the response model in FastAPI.
The Basics of Response Model
First, let's understand what a response model is. In FastAPI, a response model is a Python class that defines the data structure that your API will return to the client.
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
In this example, Item
is our response model. It has attributes name
, description
, price
, and tax
, all of which are typed.
Customizing the Response Model
When you define a route operation, you can set the response_model
parameter with a Pydantic model. FastAPI will use this model to:
- Convert the output data to the Python data types declared in the model.
- Validate the data.
- Add a JSON Schema in the OpenAPI path operation that corresponds to the model.
- Use the model for automatic API documentation.
Let's customize the response model for an API endpoint that retrieves an item by ID.
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
# Your data retrieval and processing logic here
...
In this example, FastAPI uses the Item
response model to format and validate the data returned by our read_item()
function.
Response Model Encoding Parameters
FastAPI provides you with a response_model
attribute, response_model_exclude_unset
. By default, it's set to False
. If you set it to True
, it will not include the model's default values in the response.
@app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
async def read_item(item_id: int):
# Your data retrieval and processing logic here
...
In this example, the API will not return attributes with values that haven't been set.
Conclusion
In this tutorial, you learned the basics of response models, how to customize them, and how to further tweak the response using encoding parameters. Customizing response models is an essential tool in creating APIs that are secure, reliable, and easy to use.
Remember, a good understanding of FastAPI response models will greatly improve the quality of your API, so keep practicing and exploring different possibilities!