response_model parameter allows you to define the structure of your API responses, providing automatic validation, serialization, and documentation.
Basic Response Model
Useresponse_model to declare what your endpoint returns:
FastAPI uses the
response_model to:- Convert the output data to the declared type
- Validate the data
- Add a JSON Schema for the response in the OpenAPI docs
- Limit the output data to what’s in the model
Return Type Annotations
You can also use return type annotations (Python 3.9+):Response Model vs Return Type
Filtering Response Data
One of the most powerful features is automatic filtering of response data:Response Model with Default Values
You can exclude fields with default values from the response:1
response_model_exclude_unset=True
Don’t include fields that weren’t explicitly set
2
response_model_exclude_defaults=True
Don’t include fields with their default values
3
response_model_exclude_none=True
Don’t include fields with None values
Include and Exclude Fields
You can explicitly include or exclude specific fields:Use sets (not lists) for
response_model_include and response_model_exclude.Multiple Models Pattern
Create separate models for input and output:Union Response Types
Return different model types based on conditions:The response will match whichever model is appropriate based on the data structure.
Response Model Benefits
1
Security
Automatically filters sensitive data like passwords
2
Documentation
Generates accurate OpenAPI schema for responses
3
Validation
Validates outgoing data, catching bugs early
4
Serialization
Converts complex types to JSON-compatible formats
5
Type Safety
Provides editor autocomplete and type checking
Disabling Response Model
In rare cases, you can disable response validation:Related Topics
- Extra Models - Work with multiple related models
- Response Status Code - Customize HTTP status codes
- Request Body - Define request schemas