FastAPI Response Models
What are response models in FastAPI?
Response models in FastAPI define the structure and format of the data that an API returns to the client. By specifying a response model using Pydantic, FastAPI automatically validates and serializes the response data, ensuring that the API returns consistent and well-structured data to the client.
How do you use response models in FastAPI?
You can define a response model in FastAPI by specifying it in the response_model parameter of the route decorator. The response model is a Pydantic model that dictates the structure of the data returned by the API.
Example of using a response model:
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
return {"name": "Sample Item", "price": 12.99}
In this example, the Item model is specified as the response_model for the read_item route. FastAPI will automatically validate and serialize the response to match the Item model.
How do you filter response fields using response models in FastAPI?
FastAPI allows you to exclude certain fields from the response model when returning data. You can use the exclude parameter in the model's .dict() method to filter out specific fields from the response.
Example of filtering response fields:
from pydantic import BaseModel
class User(BaseModel):
username: str
email: str
password: str
@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: int):
user = {"username": "johndoe", "email": "[email protected]", "password": "supersecret"}
return {k: v for k, v in user.items() if k != "password"}
In this example, the password field is excluded from the response by using a Python dictionary comprehension. The response_model still expects the structure defined in the User model, but the password is not returned.
How do you handle nested response models in FastAPI?
FastAPI allows you to use nested Pydantic models as response models. This is useful when you need to return hierarchical or complex data structures in your API response.
Example of using nested response models:
from pydantic import BaseModel
class Address(BaseModel):
city: str
state: str
class User(BaseModel):
username: str
address: Address
@app.get("/users/{user_id}", response_model=User)
def read_user(user_id: int):
return {
"username": "johndoe",
"address": {"city": "New York", "state": "NY"}
}
In this example, the User model contains a nested Address model, and FastAPI automatically validates and serializes the response to match this nested structure.
How do you handle list responses with response models in FastAPI?
FastAPI allows you to return lists of data by specifying a list of Pydantic models as the response model. This is useful when an API needs to return a collection of objects, such as a list of items or users.
Example of returning a list with response models:
from typing import List
class Item(BaseModel):
name: str
price: float
@app.get("/items/", response_model=List[Item])
def read_items():
return [
{"name": "Item 1", "price": 12.99},
{"name": "Item 2", "price": 23.50}
]
In this example, the response_model is a list of Item models, and FastAPI validates that each object in the list matches the Item model before returning the response.
How do you customize the response status code in FastAPI?
FastAPI allows you to customize the response status code by using the status_code parameter in the route decorator. This is useful when you need to return a specific HTTP status code for certain responses, such as 201 Created for a successful POST request.
Example of customizing the response status code:
from fastapi import FastAPI, status
class Item(BaseModel):
name: str
price: float
@app.post("/items/", response_model=Item, status_code=status.HTTP_201_CREATED)
def create_item(item: Item):
return item
In this example, the status_code parameter is set to 201 Created for the create_item route, indicating that the item was successfully created.
How do you handle multiple responses with different status codes in FastAPI?
FastAPI allows you to handle multiple response types and status codes using the responses parameter in the route decorator. This is useful when an API can return different status codes depending on the outcome of the request (e.g., 200 OK for success or 404 Not Found for missing data).
Example of handling multiple responses:
from fastapi import FastAPI, HTTPException
class Item(BaseModel):
name: str
price: float
@app.get("/items/{item_id}", response_model=Item, responses={404: {"description": "Item not found"}})
def read_item(item_id: int):
if item_id != 1:
raise HTTPException(status_code=404, detail="Item not found")
return {"name": "Sample Item", "price": 12.99}
In this example, the route can return a 200 OK response with the item data, or a 404 Not Found error if the item does not exist. The responses parameter is used to document the possible responses.
How do you include metadata in response models in FastAPI?
FastAPI allows you to add metadata, such as examples, descriptions, and titles, to response models using the schema_extra attribute in the Pydantic model's Config class. This metadata is automatically included in the API documentation.
Example of adding metadata to a response model:
class Item(BaseModel):
name: str
price: float
class Config:
schema_extra = {
"example": {
"name": "Sample Item",
"price": 12.99
}
}
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
return {"name": "Sample Item", "price": 12.99}
In this example, the Item model includes an example in the schema_extra attribute. The example is automatically displayed in the API documentation (e.g., Swagger UI), showing a sample response for the model.
How do you exclude certain fields from a response model in FastAPI?
FastAPI allows you to exclude specific fields from the response model using the response_model_exclude parameter in the route decorator. This is useful if you want to hide sensitive or unnecessary fields from the response.
Example of excluding fields from a response model:
class User(BaseModel):
username: str
email: str
password: str
@app.get("/users/{user_id}", response_model=User, response_model_exclude={"password"})
def read_user(user_id: int):
return {"username": "johndoe", "email": "[email protected]", "password": "supersecret"}
In this example, the password field is excluded from the response, even though it is defined in the User model. FastAPI ensures that the password is not included in the response sent to the client.
How do you handle response validation in FastAPI?
FastAPI automatically validates the response data using the specified response model. If the returned data does not match the response model, FastAPI raises a validation error. This ensures that the response adheres to the defined structure.
Example of response validation:
class Item(BaseModel):
name: str
price: float
@app.get("/items/{item_id}", response_model=Item)
def read_item(item_id: int):
return {"name": "Sample Item"} # Missing "price" field will raise a validation error
In this example, the response is missing the price field required by the Item model. FastAPI raises a validation error because the response does not match the expected structure.