FASTAPI / 2. PYDANTIC & REQUEST BODIES
Pydantic Models & Request Bodies
Type-safe data validation for everything that comes in and goes out
EXPLANATION
Pydantic is the heart of FastAPI. Every piece of data that enters or leaves your API is validated, coerced, and documented through Pydantic models. A Pydantic model is a Python class that inherits from BaseModel. Every field with a type annotation is automatically validated. Pydantic v2 (the current version) is compiled in Rust — validation is extremely fast. When you type-hint a function parameter as a Pydantic model, FastAPI knows it must come from the request body (JSON). It parses the JSON → validates every field → calls your function with a fully valid Python object. Invalid data returns 422 with detailed error messages automatically. Field() adds constraints and metadata: • gt, ge, lt, le → numeric bounds • min_length, max_length → string bounds • pattern → regex validation • description, example → shows in /docs Nested models work naturally — a model can have fields that are themselves Pydantic models, or lists of models. FastAPI handles deep serialization automatically. model_config with json_schema_extra adds example payloads to /docs so frontend developers know exactly what to send. Optional fields use type | None = None (Python 3.10+) or Optional[type] = None. Required fields have no default. Validators using @field_validator let you write custom validation logic — password confirmation, cross-field checks, business rules.
ARCHITECTURE
REQUEST JSON:
{
"name": "Laptop",
"price": 999.99,
"in_stock": true,
"tags": ["electronics", "computers"]
}
↓ FastAPI parses body
┌──────────────────────────────────────────┐
│ Pydantic validates field by field: │
│ name: str → "Laptop" ✓ │
│ price: float → 999.99 ✓ │
│ in_stock: bool → True ✓ │
│ tags: list[str] → [...] ✓ │
│ description: None → None (optional) ✓ │
└──────────────────────────────────────────┘
↓ Your function receives
item: Item ← fully validated Python object
item.name → "Laptop"
item.price → 999.99 (float, not string)CODE