How to Use Pydantic for Response Model in FastAPI
In FastAPI, use
pydantic models to define the response_model parameter in your route decorators. This tells FastAPI to validate and serialize the output data automatically using the specified Pydantic model.Syntax
To use a Pydantic model as a response model in FastAPI, define a class that inherits from BaseModel. Then, specify this class in the response_model argument of your route decorator. FastAPI uses this model to validate and format the response data.
Parts explained:
BaseModel: Base class from Pydantic to create data models.response_model=YourModel: Tells FastAPI to use this model for the response.@app.get(): The route decorator where you specify the response model.
python
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", "price": 10.5}
Example
This example shows a FastAPI app with a Pydantic model Item used as the response model. When you call the endpoint, FastAPI returns data validated and serialized according to Item.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float description: str | None = None @app.get("/items/{item_id}", response_model=Item) def read_item(item_id: int): # Simulate fetching data return { "name": "Coffee", "price": 5.99, "description": "A hot drink" }
Output
GET /items/1
{
"name": "Coffee",
"price": 5.99,
"description": "A hot drink"
}
Common Pitfalls
Common mistakes when using Pydantic response models in FastAPI include:
- Returning data that does not match the model fields, causing validation errors.
- Not using
response_modeland returning raw dicts, which skips validation and serialization. - Modifying the returned data after validation, which can cause inconsistencies.
Always ensure your returned data matches the Pydantic model structure exactly.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class User(BaseModel): username: str age: int # Wrong: returning extra fields not in model @app.get("/users/{user_id}", response_model=User) def get_user(user_id: int): return {"username": "alice", "age": 30, "extra": "not allowed"} # This will cause validation error # Correct: return only model fields @app.get("/users/{user_id}/correct", response_model=User) def get_user_correct(user_id: int): return {"username": "alice", "age": 30}
Quick Reference
| Concept | Description |
|---|---|
| BaseModel | Base class to define data models with fields and types |
| response_model | Parameter in route decorator to specify output model |
| Validation | FastAPI validates returned data against the response model |
| Serialization | Response data is converted to JSON using the model |
| Optional fields | Use Optional or default values in Pydantic models |
Key Takeaways
Use Pydantic models with BaseModel to define response schemas in FastAPI.
Set the response_model parameter in route decorators to enable automatic validation and serialization.
Returned data must match the Pydantic model fields to avoid validation errors.
Pydantic models help keep API responses consistent and clear.
Use optional fields in models to handle missing data gracefully.