Skip to main content
When you need to send data from a client to your API, you send it as a request body. FastAPI uses Pydantic models to declare, validate, and document request bodies.

Pydantic Models

Create a Pydantic model to define the structure of your request body:
This endpoint:
  • Accepts POST requests to /items/
  • Expects a JSON body matching the Item model
  • 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.price
2

Convert to Dict

Use item.model_dump() to get a dictionary
3

Validation

All validation happens automatically before your function runs

Request Body + Path Parameters

You can declare both path parameters and a request body:
FastAPI will:
  • Extract item_id from 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:
Expected JSON body:

Using Body() for Additional Validation

Import and use Body() for additional validation and metadata:
The embed=True parameter tells FastAPI to expect the body nested under a key matching the parameter name.

Field Validation

Use Pydantic’s Field() 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:
FastAPI will validate the entire nested structure, including lists and deeply nested 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