All concepts

Pydantic

Typed models validate and coerce untrusted input at the boundary, with clear errors.

Python · Intermediate · ~5 min

In plain English

Declare the shape your data must have, and it checks and converts incoming values for you — rejecting anything that doesn't fit.

Why it's worth your time

It's the boundary guard for every API and every LLM response you parse, and it's what makes structured output actually safe.

If you remember three things

  • Validation and coercion driven by type hints
  • Errors are structured and specific to the field
  • The same model doubles as a JSON schema

Overview

Pydantic turns a class of type-hinted fields into a model that validates and coerces input when constructed. Data that crosses your program's boundary—JSON, forms, env vars—is checked against the declared types; loose-but-valid values are coerced ('42' becomes 42), and bad data raises a ValidationError naming the field, value, and reason. Its v2 core is written in Rust for speed.

In an interview

Pydantic validates data at the boundary of your program. You declare a BaseModel with type-hinted fields; constructing it checks the input against those types, coerces where it safely can, and raises a detailed ValidationError otherwise. That turns untrusted JSON or config into a typed, guaranteed-valid object your code can rely on. v2 rewrote the core in Rust, so it's fast enough for hot paths, which is why FastAPI uses it for request bodies and it's the standard for settings and API schemas.

Production defaults

Validate at the edge
every external input: HTTP body, LLM output, config file
LLM output
generate the JSON schema from the model and hand it to the API's structured-output mode
Field descriptions
they become prompt text in structured output — write them for the model, not just the docs
Strictness
be strict at the boundary and permissive nowhere else

What breaks

  • Valid JSON, wrong meaning — Schema enforced structure, not semantics. Add validators for business rules.
  • Silent type coercion surprised you — Pydantic coerces by default. Use strict mode where a string '1' must not become an int.

Watch it explained

What is Pydantic? Python Data Validation Made Easy! 🐍✨ — PyGuess , 3:16

Related