Pydantic Models in Python

From the FastAPI cheat sheet · Request Body & Pydantic Models · verified Jul 2026

Pydantic Models

Define request and response schemas with automatic validation.

python
from pydantic import BaseModel, Field

class Item(BaseModel):
    name: str
    price: float = Field(gt=0, description="Must be positive")
    description: str | None = None
    tags: list[str] = []

@app.post("/items/")
async def create_item(item: Item):
    return item
💡 Pydantic model parameters are automatically parsed from the JSON request body
⚡ Use Field() for validation: gt, ge, lt, le (numbers), min_length, max_length (strings)
📌 Nested models are fully validated — define Address as a model and use it inside User
🟢 FastAPI auto-detects: path params from URL, body from Pydantic models, rest as query
pydanticmodelsbodyvalidation

Continue with FastAPI

Save the full cheat sheet or work through every related task.

More Python tasks

Back to the full FastAPI cheat sheet