Pydantic

Python data validation library using type hints. The backbone of FastAPI, LLM structured output, and a lot of modern Python codebases.

Category
Infrastructure
Difficulty
Beginner
When to use
Validating or serializing structured data in Python — API payloads, configuration, LLM outputs, anything with a schema.
When not to use
Hot inner loops where validation overhead matters and the data is already trusted.
Alternatives
dataclasses attrs marshmallow msgspec

At a glance

FieldValue
CategoryValidation / data modeling
DifficultyBeginner
When to useTyped data models, API schemas, LLM output parsing
When not to usePerformance-critical inner loops
Alternativesdataclasses, attrs, msgspec

What it is

Pydantic lets you define models with Python type hints and get automatic validation, serialization, and JSON Schema generation for free. Pydantic v2 rewrote the core in Rust and is roughly an order of magnitude faster than v1.

When we reach for it at Ephizen

  • Every FastAPI request and response body.
  • Configuration objects loaded from env vars with pydantic-settings.
  • Structured LLM outputs — pass a Pydantic schema to OpenAI/Anthropic’s tool-calling API and get a validated object back.
  • Data contracts between internal services.

Getting started

from pydantic import BaseModel, Field

class ChatRequest(BaseModel):
    user_id: str
    messages: list[str] = Field(min_length=1)
    temperature: float = Field(0.2, ge=0, le=2)

ChatRequest.model_validate({"user_id": "u1", "messages": ["hi"]})

Gotchas

  • v1 → v2 migration is real: .dict() became .model_dump(), validators changed shape, and config classes moved. Pin majors.
  • Pydantic can’t validate what the type system can’t express. For cross-field rules use model_validator.
  • JSON Schema export is useful but not identical to OpenAPI — FastAPI handles the translation.

Related tools