Pydantic Models
Create a Pydantic model to define the structure of your request body:- Accepts POST requests to
/items/ - Expects a JSON body matching the
Itemmodel - Automatically validates the data
- Provides interactive API docs
Pydantic handles all the JSON parsing, validation, and serialization automatically.
Request Body Example
Send this JSON to the endpoint:Using the Model in Your Function
You can access all model attributes directly:1
Model Attributes
Access attributes directly:
item.name, item.price2
Convert to Dict
Use
item.model_dump() to get a dictionary3
Validation
All validation happens automatically before your function runs
Request Body + Path Parameters
You can declare both path parameters and a request body:- Extract
item_idfrom the path - Parse the JSON body as an
Item
Request Body + Path + Query Parameters
You can mix all three parameter types:FastAPI automatically recognizes:
- Path parameters: If declared in the path
- Query parameters: If they’re singular types (int, str, etc.)
- Request body: If declared with a Pydantic model
Multiple Body Parameters
You can declare multiple body parameters:Using Body() for Additional Validation
Import and useBody() for additional validation and metadata:
Field Validation
Use Pydantic’sField() for field-level validation:
Available Field() Parameters
- Numeric:
gt,ge,lt,le,multiple_of - String:
min_length,max_length,pattern - General:
default,description,examples,deprecated
Nested Models
Pydantic models can contain other models:Key Benefits
- Automatic Validation: Invalid data returns 422 with details
- Automatic Documentation: Models appear in OpenAPI/Swagger UI
- Type Safety: Full editor support with autocomplete
- Serialization: Automatic JSON parsing and encoding
- Data Conversion: Automatic type conversion where possible
Related Topics
- Request Forms - Handle form data instead of JSON
- Request Files - Handle file uploads
- Response Model - Define response schemas
- Extra Models - Work with multiple related models