The Problem: Multiple Models Needed
For a single resource (like a user), you often need different models:- Input model: Accepts user data including passwords
- Output model: Returns data without sensitive information
- Database model: Includes internal fields like hashed passwords
Model Inheritance
Use Pydantic model inheritance to reduce duplication:1
UserBase
Contains common fields shared across all models
2
UserIn
Adds
password field for accepting input3
UserOut
Uses only base fields for secure output
4
UserInDB
Adds
hashed_password for database storageUnion Types for Multiple Response Models
Return different models based on conditions:FastAPI will automatically match the response to the correct model based on the data structure.
List of Models
Return lists of model instances:Dict Response Model
Return arbitrary dict responses:While
dict[str, float] provides type hints, it doesn’t offer field-level validation like Pydantic models.Model Composition
Compose models by including other models as fields:Nested Model Example
Deeply Nested Models
You can nest models as deeply as needed:Generic Models with Type Variables
Create generic response wrappers:Model Config and Settings
Customize model behavior with configuration:When to Use Multiple Models
1
Security
Separate input/output models to exclude sensitive data
2
API Versions
Different models for different API versions
3
User Roles
Different response models based on user permissions
4
Resource States
Different models for resource creation vs retrieval
Best Practices
Related Topics
- Response Model - Learn about response_model parameter
- Request Body - Define request schemas
- Extra Data Types - Use specialized field types