4. Request Bodies & Pydantic Models

Why Dictionaries Are Dangerous

Using raw dictionaries for request bodies provides no structural guarantees and allows malformed or incomplete data to pass silently. This approach shifts validation responsibility into business logic, increasing complexity and the risk of runtime errors. In production systems, such implicit assumptions often lead to fragile and insecure APIs.


Schema as a Contract

Pydantic models in FastAPI define an explicit contract for request bodies. They describe the expected structure, data types, and constraints of incoming data in a declarative manner. This contract is enforced automatically, ensuring that only valid and well-formed input reaches application logic.

from pydantic import BaseModel

class UserCreate(BaseModel):
    name: str
    email: str
    age: int

Nested Models

Pydantic supports nested models to represent complex request structures. This allows APIs to model real-world data relationships while preserving clarity and validation at every level. Nested schemas improve expressiveness without sacrificing correctness or readability.

class Address(BaseModel):
    city: str
    country: str

class UserCreate(BaseModel):
    name: str
    address: Address

Input Validation as a Security Layer

FastAPI treats input validation as a primary security mechanism rather than a secondary concern. By rejecting invalid or unexpected data at the boundary, the framework reduces exposure to injection attacks and logic errors. Strong validation limits the attack surface before requests interact with internal systems.

Last updated