How to Use Nested Pydantic Models in FastAPI
In FastAPI, you can use nested
Pydantic models by defining one model inside another as a field type. This allows you to structure complex data easily, and FastAPI will automatically validate and parse nested JSON objects in requests and responses.Syntax
To use nested Pydantic models in FastAPI, define a Pydantic model as a field inside another model. The outer model includes the inner model as a type annotation for one of its fields.
This tells FastAPI to expect a nested JSON object matching the inner model's structure.
python
from pydantic import BaseModel class InnerModel(BaseModel): name: str age: int class OuterModel(BaseModel): id: int details: InnerModel
Example
This example shows a FastAPI app with a POST endpoint that accepts a nested Pydantic model. The OuterModel contains an InnerModel as a field. FastAPI validates the nested JSON automatically.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class InnerModel(BaseModel): name: str age: int class OuterModel(BaseModel): id: int details: InnerModel @app.post("/items/") async def create_item(item: OuterModel): return {"item_id": item.id, "name": item.details.name, "age": item.details.age}
Output
POST /items/ with JSON {"id": 1, "details": {"name": "Alice", "age": 30}} returns {"item_id": 1, "name": "Alice", "age": 30}
Common Pitfalls
- Forgetting to use a Pydantic model as the nested type and using a plain dict instead will disable validation.
- Not matching the JSON structure to the nested model fields causes validation errors.
- Using mutable default values for nested models can cause unexpected behavior; always use Pydantic models without defaults or use
Field(default_factory=...).
python
from pydantic import BaseModel # Wrong: Using dict disables validation class OuterModelWrong(BaseModel): id: int details: dict # No validation on nested data # Right: Use nested Pydantic model class InnerModel(BaseModel): name: str age: int class OuterModelRight(BaseModel): id: int details: InnerModel
Quick Reference
Tips for nested Pydantic models in FastAPI:
- Define inner models as subclasses of
BaseModel. - Use inner models as field types in outer models.
- FastAPI auto-validates nested JSON matching the model structure.
- Use nested models for clear, maintainable data schemas.
- Always test with example JSON to ensure validation works as expected.
Key Takeaways
Use Pydantic models as types inside other models to create nested schemas.
FastAPI automatically validates nested JSON data based on nested models.
Avoid using plain dicts for nested fields to keep validation strict.
Match your JSON structure exactly to the nested model fields to prevent errors.
Test your API with nested JSON to confirm correct parsing and validation.