Pydantic
02 / 02

Nested Models, Settings & FastAPI Integration

Nested Models, Settings & FastAPI Integration

Nested Models & Separate Request/Response Schemas

class LineItem(BaseModel):
    sku: str
    quantity: int

class Order(BaseModel):
    id: int
    items: list[LineItem]

class UserCreate(BaseModel):
    email: str
    password: str

class UserOut(BaseModel):
    id: int
    email: str  # no password field — never leaked in a response

A model can contain fields typed as other models (or lists of them), validating nested JSON recursively as one coherent schema. Using separate models for a create-request (UserCreate) vs. a response (UserOut) prevents accidentally leaking sensitive fields like a plaintext password that should never leave the server.

Settings from the Environment

from pydantic_settings import BaseSettings

class Settings(BaseSettings):
    database_url: str
    debug: bool = False

settings = Settings()  # populated + validated from env vars / .env

BaseSettings applies the same typed validation to application configuration, populated from environment variables. Validating config at startup catches missing/malformed values immediately with a clear error, instead of a confusing failure deep in the code later when an unvalidated raw string is finally used.

FastAPI & Auto-Generated Docs

FastAPI is built around Pydantic models as request/response schemas — parsing and validating incoming JSON automatically, and introspecting the same model definitions to generate interactive OpenAPI/Swagger documentation, so docs never drift from actual validation logic.

Pydantic v2: Rust Core

Pydantic v2's core validation logic was rewritten in Rust as the separate pydantic-core library, delivering significant validation speedups over v1's pure-Python implementation while keeping a similar (not fully backward-compatible) Python API.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free