Skip to main content
The response_model parameter allows you to define the structure of your API responses, providing automatic validation, serialization, and documentation.

Basic Response Model

Use response_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+):
Using return type annotations is the modern, recommended approach. It provides better type checking in your editor.

Response Model vs Return Type

Filtering Response Data

One of the most powerful features is automatic filtering of response data:
Even though user_saved contains hashed_password, only the fields in UserOut are returned to the client. The password is automatically filtered out.

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:
Only disable response models when absolutely necessary. You lose validation and documentation benefits.