Skip to content

Sending Data: Request Body and Pydantic

When you need to send data from a client (like a browser) to your API, you typically send it as a Request Body. The most common format for this is JSON. To declare a request body in FastAPI, you use Pydantic models.

Pydantic is a library that allows you to define the “shape” or schema of your data using Python classes. You define a class that inherits from BaseModel, and declare attributes with standard Python types.

from typing import Union
from fastapi import FastAPI
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Union[str, None] = None
price: float
is_offer: bool = False
app = FastAPI()

In this Item model:

  • name and price are required (no default values).
  • description is optional and defaults to None.
  • is_offer is optional and defaults to False.

To receive this data in your API, declare it as a parameter in your path operation function and use the Pydantic model class as the type hint.

@app.post("/items/")
def create_item(item: Item):
# FastAPI converts the JSON body into an 'item' object
return item

When a user sends a POST request to /items/, FastAPI will automatically:

  1. Read the body as JSON.
  2. Convert the corresponding types (if needed).
  3. Validate the data against the Item model.
  4. Give you the data in the function as the item parameter. You even get code completion for attributes like item.name inside your function!

If the client sends invalid data—for example, sending a string “twenty” for the price field (which expects a float)—FastAPI will automatically return a 422 Unprocessable Entity error.

The response body will contain a clear JSON indication of exactly what went wrong and where, helping the client fix their request without you needing to write custom validation logic.