How to Validate Request Body in FastAPI Quickly and Easily
In FastAPI, you validate the request body by defining a
Pydantic model that describes the expected data structure and types, then use it as a function parameter with Body. FastAPI automatically checks the incoming JSON against this model and returns errors if the data is invalid.Syntax
To validate a request body in FastAPI, define a Pydantic model class with fields and types representing the expected data. Then, use this model as a parameter in your path operation function with Body from fastapi. FastAPI uses this to parse and validate the incoming JSON.
- Pydantic model: Defines the data structure and validation rules.
- Function parameter: Accepts the validated data automatically.
- Body: Marks the parameter as coming from the request body.
python
from fastapi import FastAPI, Body from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool = None @app.post("/items/") async def create_item(item: Item = Body(...)): return item
Example
This example shows a FastAPI app that validates a JSON request body with fields name, price, and an optional is_offer. If the client sends invalid data, FastAPI returns a clear error response.
python
from fastapi import FastAPI, Body from pydantic import BaseModel app = FastAPI() class Item(BaseModel): name: str price: float is_offer: bool = None @app.post("/items/") async def create_item(item: Item = Body(...)): return {"message": "Item received", "item": item.dict()}
Output
POST /items/ with JSON {"name": "Book", "price": 12.5}
Response:
{
"message": "Item received",
"item": {
"name": "Book",
"price": 12.5,
"is_offer": null
}
}
Common Pitfalls
Common mistakes when validating request bodies in FastAPI include:
- Not using a
Pydanticmodel and trying to parse raw JSON manually. - Forgetting to import or use
Bodywhen needed, which can cause unexpected behavior. - Using incorrect field types that don't match the incoming data, causing validation errors.
- Not handling optional fields properly, leading to errors if they are missing.
Always define clear models and use Body(...) to require the body.
python
from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() # Wrong: no Pydantic model, no validation @app.post("/wrong/") async def wrong_endpoint(item: dict): return item # Right: use Pydantic model and Body from fastapi import Body class Item(BaseModel): name: str price: float @app.post("/right/") async def right_endpoint(item: Item = Body(...)): return item
Quick Reference
Tips for validating request bodies in FastAPI:
- Use
Pydantic BaseModelto define expected data. - Use
Body(...)to mark required request body parameters. - Optional fields can have default values or
None. - FastAPI automatically returns detailed error messages on validation failure.
- Use type hints for clear and automatic validation.
Key Takeaways
Use Pydantic models to define and validate request body data in FastAPI.
Mark request body parameters with Body(...) to enforce validation.
FastAPI automatically returns clear error responses for invalid data.
Define optional fields with default values or None in your models.
Avoid manual JSON parsing; rely on FastAPI and Pydantic for safety and simplicity.