FastAPI Response Model
Response models are used to declare the data structure returned by the API. By declaring a response model, FastAPI automatically validates, serializes, and filters output data, ensuring that clients receive only the expected data.
Using return type annotations
The simplest way is to directly annotate the return type of the path operation function:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
app
=
FastAPI
(
)
class
Item
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
@
app.
get
(
"/items/{item_id}"
,
response_model
=
Item
)
async
def
read_item
(
item_id:
int
)
:
The returned data is automatically filtered and validated according to the Item model
return
{
"name"
:
"Foo"
,
"description"
:
"A very nice Item"
,
"price"
:
22.2
,
"secret"
:
"this should not be visible"
,
Fields not in Item are filtered out
}
FastAPI uses response models to do the following:
| Function | Description |
|---|---|
| Data validation | If the returned data does not match the model, there is a problem with the application code |
| Data Filtering | Only return fields defined in the model, filtering out extra fields (this is important for security) |
| Generate documentation | Display the response structure in the OpenAPI documentation |
| Serialization | Use Pydantic (implemented in Rust) to efficiently convert data to JSON |
The response_model parameter
When the return type does not match the response model, use the decorator's response_model Parameters:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
,
EmailStr
app
=
FastAPI
(
)
Input model (includes password)
class
UserIn
(
BaseModel
)
:
username:
str
password:
str
: EmailStr
Output model (excludes password)
class
UserOut
(
BaseModel
)
:
username:
str
: EmailStr
The function receives UserIn, but the response uses UserOut
@
app.
post
(
"/users/"
,
response_model
=
UserOut
)
async
def
create_user
(
user
: UserIn
)
:
The returned user contains a password, but response_model=UserOut filters out the password
return
user
This is an important way to protect sensitive data. Using different input and output models ensures that sensitive fields such as passwords never appear in API responses.
Return types and data filtering
It is recommended to use class inheritance to separate input/output models, so that editors and mypy can correctly understand the types, while FastAPI can filter the data:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
,
EmailStr
app
=
FastAPI
(
)
Base user model
class
BaseUser
(
BaseModel
)
:
username:
str
: EmailStr
Input model: inherits from the base model, adds a password field
class
UserIn
(
BaseUser
)
:
password:
str
@
app.
post
(
"/users/"
)
async
def
create_user
(
user
: UserIn
)
BaseUser:
Return type annotated as BaseUser, FastAPI filters out the password field
Editors and mypy are also satisfied because UserIn is a subclass of BaseUser
return
user
Exclude unset default values
Use response_model_exclude_unset=True, returning only fields that actually have values set:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
app
=
FastAPI
(
)
class
Item
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
tax:
float
=
10.5
tags:
list
[
str
]
=
[
]
items
=
{
"foo"
:
{
"name"
:
"Foo"
,
"price"
:
50.2
}
,
"bar"
:
{
"name"
:
"Bar"
,
"description"
:
"The bartenders"
,
"price"
:
62
,
"tax"
:
20.2
}
,
"baz"
:
{
"name"
:
"Baz"
,
"description"
:
None
,
"price"
:
50.2
,
"tax"
:
10.5
,
"tags"
:
[
]
}
,
}
@
app.
get
(
"/items/{item_id}"
,
response_model
=
Item
,
response_model_exclude_unset
=
True
)
async
def
read_item
(
item_id:
str
)
:
return
items
[
item_id
]
Comparison of responses for different item_ids:
| item_id | Response | Description |
|---|---|---|
foo |
{"name": "Foo", "price": 50.2} |
Only explicitly set fields are returned, default values are omitted |
bar |
{"name": "Bar", "description": "...", "price": 62, "tax": 20.2} |
All fields have actual values and are all returned |
Related filtering parameters:
| Parameters | Description |
|---|---|
response_model_exclude_unset |
Exclude fields with unset values |
response_model_exclude_defaults |
Exclude fields whose value equals the default |
response_model_exclude_none |
Exclude fields whose value is None |
Include/exclude specific fields
Use response_model_include and response_model_exclude Precisely control output fields:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
app
=
FastAPI
(
)
class
Item
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
tax:
float
=
10.5
Include only name and description
@
app.
get
(
"/items/{item_id}"
,
response_model
=
Item
,
response_model_include
=
{
"name"
,
"description"
}
)
async
def
read_item_name
(
item_id:
str
)
:
return
items
[
item_id
]
Exclude tax
@
app.
get
(
"/items/{item_id}/no-tax"
,
response_model
=
Item
,
response_model_exclude
=
{
"tax"
}
)
async
def
read_item_no_tax
(
item_id:
str
)
:
return
items
[
item_id
]
Although
response_model_includeandresponse_model_excludeFields can be filtered quickly, but it is recommended to use multiple model classes instead, because they cannot remove excluded fields from the OpenAPI documentation.
Summary
- Use
response_modelDeclare a response model via a parameter or return type annotation - The core role of response models is data filtering, protecting sensitive data from being leaked
- Use different models for input and output to ensure fields like passwords do not appear in responses
response_model_exclude_unsetOnly return fields that are actually set- It is recommended to use model inheritance + return type annotations rather than
response_model_include/exclude