How to Get Request Body in FastAPI: Simple Guide
from pydantic import BaseModel to define the expected body structure, and FastAPI automatically parses the JSON body into that model.Syntax
To get the request body in FastAPI, define a Pydantic model class that describes the expected data structure. Then, add a parameter of that model type to your path operation function. FastAPI reads the JSON body and converts it into the model instance.
Example parts:
class Item(BaseModel):defines the data model.item: Itemin the function parameters tells FastAPI to expect and parse the request body.- Return or use
iteminside the function as a normal Python object.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.post("/items/") def create_item(item: Item): return item
Example
This example shows a FastAPI app that accepts a JSON body with name and price fields. When you send a POST request to /items/ with JSON data, FastAPI parses it into an Item object and returns it.
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float @app.post("/items/") def create_item(item: Item): return {"item_name": item.name, "item_price": item.price}
Common Pitfalls
1. Missing Pydantic model: You must define a Pydantic model to parse the body; using plain dict or other types without annotation won't parse JSON automatically.
2. Forgetting to declare the parameter: If you don't add the model parameter to the function, FastAPI won't read the body.
3. Sending wrong content type: The client must send Content-Type: application/json header; otherwise, FastAPI won't parse the body as JSON.
from fastapi import FastAPI app = FastAPI() # Wrong: no model, no body parsing @app.post("/wrong/") def wrong_endpoint(data): return data # Right: with Pydantic model from pydantic import BaseModel class DataModel(BaseModel): field: str @app.post("/right/") def right_endpoint(data: DataModel): return data
Quick Reference
Summary tips for getting request body in FastAPI:
- Define a Pydantic model to describe the body.
- Use the model as a function parameter to get parsed data.
- Ensure client sends JSON with correct
Content-Type. - Access the body data as normal Python attributes.