FastAPI Pydantic Models
Pydantic is a core dependency of FastAPI, used for data validation and serialization. It lets you define data models using standard Python type annotations, automatically handling validation, type conversion, and documentation generation.
What is Pydantic
Pydantic is a Python data validation library. Its core idea is:define data structures with Python type annotations, and Pydantic automatically handles validation and conversion. In FastAPI, Pydantic is mainly used for:
| Purpose | Description |
|---|---|
| Request body validation | automatically validate that the JSON data sent by the client matches the model definition |
| Response body serialization | automatically convert model data into a JSON response |
| Automatic documentation | The model's fields, types, and validation rules automatically appear in the API docs |
| Editor support | Model attributes get full autocompletion in the editor |
Define a Pydantic model
Create a class that inherits from BaseModel , and declare fields using standard Python types:
Example
from
pydantic
import
BaseModel
class
Item
(
BaseModel
)
:
name:
str
Required: item name
description:
str
|
None
=
None
Optional: item description
price:
float
Required: item price
tax:
float
|
None
=
None
Optional: tax
Whether a field is required depends on whether it has a default value:
| Field | Declaration Method | Required |
|---|---|---|
name |
name: str |
Required |
description |
description: str \| None = None |
Optional |
price |
price: float |
Required |
tax |
tax: float \| None = None |
Optional |
Using Pydantic models
as the request body
The most common use is to declare the model as a parameter 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
tax:
float
|
None
=
None
@
app.
post
(
"/items/"
)
async
def
create_item
(
item: Item
)
:
FastAPI automatically validates the request body and, after validation, assigns it to the item parameter
return
item
Accessing and manipulating model data
Example
@
app.
post
(
"/items/"
)
async
def
create_item
(
item: Item
)
:
Access model attributes
(
item.
name
)
Access attributes directly
(
item.
price
)
The editor provides autocompletion
Serialize to a dictionary
item_dict
=
item.
model_dump
(
)
(
item_dict
)
{"name": "Foo", "description": None, "price": 45.2, "tax": None}
Serialize to a JSON string
item_json
=
item.
model_dump_json
(
)
(
item_json
)
'{"name":"Foo","description":null,"price":45.2,"tax":null}'
return
item_dict
Pydantic v2 uses
model_dump()andmodel_dump_json()instead of v1'sdict()andjson()method. The new method performs better (implemented in Rust under the hood).
Model validation example
When the data sent by the client does not match the model definition, FastAPI returns detailed validation errors:
Example
The client sends data missing a required field
POST /items/
{
"description"
:
"Missing name and price"
}
FastAPI returns a validation error
{
"detail"
:
[
{
"type"
:
"missing"
,
"loc"
:
[
"body"
,
"name"
]
,
"msg"
:
"Field required"
,
"input"
:
{
"description"
:
"Missing name and price"
}
}
,
{
"type"
:
"missing"
,
"loc"
:
[
"body"
,
"price"
]
,
"msg"
:
"Field required"
,
"input"
:
{
"description"
:
"Missing name and price"
}
}
]
}
If data with the wrong type is sent:
// price 应该是数字,但传了字符串
{
"name": "Foo",
"price": "not a number"
}
// FastAPI returned error
{
"detail": [
{
"type": "float_parsing",
"loc": ["body", "price"],
"msg": "Input should be a valid number, unable to parse string as a number",
"input": "not a number"
}
]
}
Common Pydantic v2 methods
| Method | v2 (recommended) | v1 (deprecated) | Description |
|---|---|---|---|
| Serialize to a dictionary | item.model_dump() |
item.dict() |
Convert the model to a Python dictionary |
| Serialize to JSON | item.model_dump_json() |
item.json() |
Convert the model to a JSON string |
| Create from a dictionary | Item.model_validate(data) |
Item.parse_obj(data) |
Create and validate a model from a dictionary |
| Create from JSON | Item.model_validate_json(json_str) |
Item.parse_raw(json_str) |
Create a model from a JSON string |
| Get the JSON Schema | Item.model_json_schema() |
Item.schema() |
Get the model's JSON Schema |
Model configuration (model_config)
Pydantic v2 uses model_config instead of v1's Config Inner class:
Example
from
pydantic
import
BaseModel
,
ConfigDict
class
Item
(
BaseModel
)
:
name:
str
price:
float
Pydantic v2 configuration style
model_config
=
ConfigDict
(
json_schema_extra
=
{
Show examples in the API docs
"examples"
:
[
{
"name"
:
"Foo"
,
"price"
:
35.4
}
]
}
)
In Pydantic v2,
orm_mode = Truehas been changed tofrom_attributes = True,schema_extrahas been changed tojson_schema_extra,allow_population_by_field_namehas been changed topopulate_by_name。
Model inheritance
Pydantic models support inheritance, making it easy to create input and output models:
Example
from
pydantic
import
BaseModel
,
EmailStr
Basic models
class
UserBase
(
BaseModel
)
:
username:
str
Required
: EmailStr
Required, email format is automatically validated
full_name:
str
|
None
=
None
Optional
Input model for creating a user (includes password)
class
UserCreate
(
UserBase
)
:
password:
str
Required
Output model for returning user information (excludes password)
class
UserOut
(
UserBase
)
:
id
:
int
Generated by the server
Usage examples
@
app.
post
(
"/users/"
,
response_model
=
UserOut
)
async
def
create_user
(
user
: UserCreate
)
:
The function receives UserCreate (with password), but the response uses UserOut (without password)
This way the password does not appear in the API response
return
{
"id"
:
1
,
**
user
.
model_dump
(
exclude
=
{
"password"
}
)
}
Using different input and output models is an important way to protect sensitive data. Never return sensitive fields such as passwords in API responses.
Summary
Key points of Pydantic models:
- Use
BaseModelDefine data models with fields declared using standard Python types - Fields with defaults are optional; fields without defaults are required
- v2 uses
model_dump()、model_validate()and other new methods - Create different input/output models through inheritance to protect sensitive data
- All validation and documentation are automatic; just declare the type once