2 Hours

4. Request Bodies & JSON Responses

Data Handling

In API development, data flows in two directions. Clients send data to your server in request bodies (typically for POST, PUT, and PATCH operations). Your server sends data back to clients in response bodies. FastAPI makes both incredibly simple with automatic JSON parsing and serialization. To test these examples, save to main.py and run uvicorn main:app --reload.

What is a Request Body?

A request body is the data that a client sends to your API. Unlike query parameters (which are part of the URL), request bodies are sent in the body of HTTP requests, typically as JSON. Request bodies are used when creating or updating resources because they can handle complex, nested data structures.

Python 3
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

# Define a Pydantic model for the request body
class UserCreate(BaseModel):
    name: str
    email: str
    age: int

@app.post("/users")
def create_user(user: UserCreate):
    # FastAPI automatically reads the JSON body, validates it,
    # and converts it to a UserCreate instance
    return {"message": f"User {user.name} created", "user": user}
Local Testing: Send a POST request to /users with JSON body: {name: Alice, email: alice@example.com, age: 30}. FastAPI validates that all required fields are present and of the correct type.

How FastAPI Reads Request Bodies

When you declare a parameter of a Pydantic model type in your path operation function, FastAPI automatically:

  1. Reads the request body as JSON
  2. Converts the JSON to a Python dictionary
  3. Validates the data against your Pydantic model (types, required fields, custom validators)
  4. Creates an instance of your Pydantic model class
  5. Injects that instance into your function parameter
Python 3
from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    tax: float = None

@app.post("/items")
def create_item(item: Item):
    total = item.price + (item.tax or 0)
    return {"name": item.name, "total": total}

Multiple Request Body Parameters

You can have multiple request body parameters in a single endpoint. FastAPI will combine them intelligently.

Python 3
class User(BaseModel):
    name: str
    email: str

class Address(BaseModel):
    street: str
    city: str
    zipcode: str

@app.post("/users/{user_id}")
def create_user_with_address(user_id: int, user: User, address: Address):
    return {
        "user_id": user_id,
        "user": user,
        "address": address
    }
Note: When you have multiple body parameters, the client must send them as nested fields in a single JSON object. FastAPI will look for keys matching the parameter names.

Optional and Default Request Body Fields

You can make fields optional by giving them default values. FastAPI will not require these fields in the request body.

Python 3
from pydantic import BaseModel
from typing import Optional

class Product(BaseModel):
    name: str                    # Required field
    description: str = ""       # Optional with default empty string
    price: float                # Required field
    discount: Optional[float] = None
    tags: list = []

@app.post("/products")
def create_product(product: Product):
    return product
Local Testing: Send a request with only name and price. FastAPI will use the default values for description, discount, and tags.

Nested Request Bodies

Pydantic models can contain other Pydantic models, allowing you to represent complex, nested JSON structures.

Python 3
class Owner(BaseModel):
    name: str
    email: str

class Pet(BaseModel):
    name: str
    species: str
    age: int

class House(BaseModel):
    address: str
    owner: Owner
    pets: list[Pet]

@app.post("/houses")
def create_house(house: House):
    return {
        "address": house.address,
        "owner_name": house.owner.name,
        "pet_count": len(house.pets)
    }

Response Models (Return Type Annotations)

You can use return type annotations to tell FastAPI what shape the response should have. This also generates accurate API documentation and filters out extra fields.

Python 3
class UserPublic(BaseModel):
    id: int
    name: str

class UserInDB(BaseModel):
    id: int
    name: str
    password: str

@app.post("/users", response_model=UserPublic)
def create_user(user: UserInDB):
    # Even if the function returns UserInDB with password,
    # FastAPI will filter it down to only UserPublic fields
    return user
Security Best Practice: Always use response_model to explicitly control what data leaves your API. Never accidentally expose password hashes or internal IDs.

Returning Lists of Models

You can return lists of models by using list[ModelName] in your response_model.

Python 3
from typing import List

class Item(BaseModel):
    id: int
    name: str
    price: float

@app.get("/items", response_model=List[Item])
def get_all_items():
    return [
        {"id": 1, "name": "Laptop", "price": 999.99},
        {"id": 2, "name": "Mouse", "price": 29.99}
    ]

Knowledge Check

Ready to test your understanding of 4. Request Bodies & JSON Responses?

Back