Request Body & Pydantic Models in FastAPI
So far, we’ve worked with routes, path parameters, and query parameters.But real-world APIs need to send and receive structured data . This is where the request body comes in.FastAPI makes handling request data extremely powerful and simple using Pydantic models.
What is a Request Body?
A request body is data sent by the client (usually in JSON format) to the API.
Example JSON:
{"name": "Laptop","price": 50000}What is Pydantic?
Pydantic is a library used by FastAPI for:
- Data validation
- Data parsing
- Type enforcement
It ensures that incoming data is correct and safe.
Creating a Pydantic Model
Let’s define a model for our API:
from pydantic import BaseModelclass Item(BaseModel):
name: str
price: floatin_stock: bool = TrueUsing Request Body in FastAPI
Now use the model in a POST request:
from fastapi import FastAPIapp = FastAPI()
@app.post("/items/")
def create_item(item: Item):
return {
"name": item.name,
"price": item.price,
"in_stock": item.in_stock}How It Works
When a request is sent:
- FastAPI reads JSON data
- Converts it into a Python object
- Validates using Pydantic
- Returns response
Automatic Validation Example
If wrong data is sent:
{"name": "Phone","price": "invalid"}FastAPI will return an error automatically:
{"detail": [{"loc": ["body", "price"],"msg": "value is not a valid float"}]}Optional Fields
You can make fields optional:
from typing import Optionalclass Item(BaseModel):name: strprice: floatdescription: Optional[str] = NoneNested Models
Pydantic supports nested data:
class Category(BaseModel):name: strclass Item(BaseModel):name: strprice: floatcategory: CategoryJSON input:
{"name": "Book","price": 300,"category": {"name": "Education"}}List Fields
You can accept lists:
from typing import Listclass Item(BaseModel):name: strtags: List[str]Organizing Models (Best Practice)
app/schemas/item.pyfrom pydantic import BaseModelclass Item(BaseModel):name: strprice: floatThen import into routes:
from app.schemas.item import ItemCommon Mistakes
1. Not using Pydantic models2. Using plain dictionaries instead of schemas3. Forgetting type hints4. Not validating nested dataKey Takeaways
- Request body is used to send structured data
- Pydantic ensures automatic validation
- FastAPI converts JSON → Python objects
- You can create nested and complex models easily
Comments
Post a Comment