4. Request Bodies & JSON Responses
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.
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}
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:
- Reads the request body as JSON
- Converts the JSON to a Python dictionary
- Validates the data against your Pydantic model (types, required fields, custom validators)
- Creates an instance of your Pydantic model class
- Injects that instance into your function parameter
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.
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 }
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.
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
Nested Request Bodies
Pydantic models can contain other Pydantic models, allowing you to represent complex, nested JSON structures.
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.
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
Returning Lists of Models
You can return lists of models by using list[ModelName] in your response_model.
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?