FastAPI Request Body Fields and Nested Models
Inside a Pydantic model, you can use Field to declare validation rules and metadata for fields, and you can also nest models to handle complex JSON data structures.
Using Field to Declare Field Validation
Just as you use Query、Path to declare validation in path operation functions, inside a Pydantic model you use Field to declare field validation:
Example
from
typing
import
Annotated
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
,
Field
app
=
FastAPI
(
)
class
Item
(
BaseModel
)
:
name:
str
=
Field
(
min_length
=
1
,
max_length
=
100
,
description
=
"Product Name"
)
Required, 1-100 characters
description:
str
|
None
=
Field
(
default
=
None
,
max_length
=
300
,
description
=
"Product Description"
)
Optional
price:
float
=
Field
(
gt
=
0
,
description
=
"Product Price"
)
Required, must be greater than 0
tax:
float
|
None
=
Field
(
default
=
None
,
ge
=
0
,
description
=
"Tax"
)
Optional, >= 0
@
app.
post
(
"/items/"
)
async
def
create_item
(
item: Item
)
:
return
item
Field Supported validation parameters:
| Parameter type | Parameters | Description |
|---|---|---|
| String validation | min_length |
Minimum length |
max_length |
Maximum length | |
pattern |
Regular expression match | |
| Numeric validation | gt |
Greater than |
ge |
Greater than or equal to | |
lt |
Less than | |
le |
Less than or equal to | |
| Metadata | title |
Field title |
description |
Field description |
Note
FieldFrom thepydanticimport, rather than fromfastapiimport. This differs fromQuery、Pathetc., which import fromfastapiimport.
List-Type Fields
You can declare a field as a list and specify the element type:
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
tags:
list
[
str
]
=
[
]
List of strings, defaults to an empty list
@
app.
post
(
"/items/"
)
async
def
create_item
(
item: Item
)
:
return
item
Request body example:
{
"name": "Foo",
"price": 42.0,
"tags": ["rock", "metal", "bar"]
}
Using Set to Deduplicate
If tags should not repeat, use set Type:
Example
class
Item
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
tax:
float
|
None
=
None
tags:
set
[
str
]
=
set
(
)
automatically removes duplicate tags
Even if the request contains duplicate tags, they are automatically deduplicated in the response.
Nested Models
A field of a Pydantic model can be another Pydantic model, supporting nesting of arbitrary depth:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
,
HttpUrl
app
=
FastAPI
(
)
Sub-model: Image
class
Image
(
BaseModel
)
:
url: HttpUrl
Automatically validates whether it is a valid URL
name:
str
Main model: Product, containing the Image sub-model
class
Item
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
tax:
float
|
None
=
None
tags:
set
[
str
]
=
set
(
)
image: Image |
None
=
None
Optional image information
@
app.
post
(
"/items/"
)
async
def
create_item
(
item: Item
)
:
return
item
Corresponding request body structure:
{
"name": "Foo",
"description": "The pretender",
"price": 42.0,
"tax": 3.2,
"tags": ["rock", "metal", "bar"],
"image": {
"url": "http://example.com/baz.jpg",
"name": "The Foo live"
}
}
Sub-models in a List
You can place sub-models in a list:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
,
HttpUrl
app
=
FastAPI
(
)
class
Image
(
BaseModel
)
:
url: HttpUrl
name:
str
class
Item
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
tax:
float
|
None
=
None
tags:
set
[
str
]
=
set
(
)
images:
list
[
Image
]
|
None
=
None
List of images
@
app.
post
(
"/items/"
)
async
def
create_item
(
item: Item
)
:
return
item
Corresponding request body:
{
"name": "Foo",
"price": 42.0,
"images": [
{"url": "http://example.com/baz.jpg", "name": "The Foo live"},
{"url": "http://example.com/dave.jpg", "name": "The Baz"}
]
}
Deeply Nested Models
You can define nested structures of arbitrary depth:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
,
HttpUrl
app
=
FastAPI
(
)
class
Image
(
BaseModel
)
:
url: HttpUrl
name:
str
class
Item
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
tax:
float
|
None
=
None
tags:
set
[
str
]
=
set
(
)
images:
list
[
Image
]
|
None
=
None
class
Offer
(
BaseModel
)
:
name:
str
description:
str
|
None
=
None
price:
float
items:
list
[
Item
]
Offer contains multiple Items, and Item in turn contains multiple Images
@
app.
post
(
"/offers/"
)
async
def
create_offer
(
offer: Offer
)
:
return
offer
Pure List Request Body
If the outermost layer of the request body is a JSON array, you can declare a list type directly in the function parameter:
Example
from
fastapi
import
FastAPI
from
pydantic
import
BaseModel
,
HttpUrl
app
=
FastAPI
(
)
class
Image
(
BaseModel
)
:
url: HttpUrl
name:
str
The request body is directly a list of Images
@
app.
post
(
"/images/multiple/"
)
async
def
create_multiple_images
(
images:
list
[
Image
]
)
:
return
images
Request Body with an Arbitrary dict
When you need to receive dictionary data with uncertain key names, you can declare a dict type of request body:
Example
from
fastapi
import
FastAPI
app
=
FastAPI
(
)
Receive a dict with int keys and float values
@
app.
post
(
"/index-weights/"
)
async
def
create_index_weights
(
weights:
dict
[
int
,
float
]
)
:
return
weights
Request body example:
{
"1": 0.5,
"2": 1.5,
"3": 2.0
}
JSON only supports string-type keys, but Pydantic automatically converts string keys to the declared type (such as
int)。
Summary
- Use Pydantic's
Fieldto add validation and metadata to model fields list[str]、set[str]and other collection types can declare list/set fields- Models can be nested, supporting JSON structures of arbitrary depth
HttpUrland other special types automatically validate formats- Pure lists and arbitrary dicts can also be used as request body types