Pydantic: Data That Validates Itself

Pydantic: Data That Validates Itself in Python: Every service that accepts data from outside faces the same problem: the data arrives as JSON, and JSON…

Concept Explanation

Every service that accepts data from outside faces the same problem: the data arrives as JSON, and JSON promises nothing. A field you expect to be an integer arrives as "42", or null, or is missing entirely. Written defensively by hand, the checks look like this:

if "email" not in payload:
    raise ValueError("email required")
if not isinstance(payload.get("age"), int):
    raise ValueError("age must be an integer")
if payload["age"] < 0:
    raise ValueError("age must be positive")

Twenty fields later this is unreadable, incomplete, and duplicated in three services.

Pydantic replaces all of it with a class whose type hints are the validation rules:

from pydantic import BaseModel, EmailStr, Field

class User(BaseModel):
    email: EmailStr
    age: int = Field(ge=0, le=130)
    nickname: str | None = None

Constructing User(**payload) now parses, coerces, validates, and raises a structured error listing every problem at once. This is why FastAPI adopted it: your type hints become the request schema, the validation layer, and the OpenAPI documentation simultaneously.

pip install "pydantic>=2" email-validator

Parse, Don't Validate

The important distinction: Pydantic does not merely check your dict and hand it back. It returns a typed object. After User.model_validate(payload) succeeds, user.age is definitely an int and definitely between 0 and 130 — everywhere downstream, forever. The uncertainty is eliminated at the boundary rather than re-checked in every function.

The Field Constraints

ConstraintApplies toMeaning
gt, ge, lt, leNumbersGreater/less than (or equal)
min_length, max_lengthstr, list, dictSize bounds
patternstrRegex the value must match
default / default_factoryAnyValue when the field is absent
aliasAnyThe name used in the incoming JSON
descriptionAnyAppears in the generated OpenAPI docs

default_factory=list is the fix for the mutable-default trap — Field(default=[]) would share one list across every instance.

v1 vs v2 Method Names

Pydantic 2 renamed the core methods. Old tutorials use the v1 names, which now emit deprecation warnings:

v1v2
.dict().model_dump()
.json().model_dump_json()
parse_obj()model_validate()
.schema().model_json_schema()
@validator@field_validator
@root_validator@model_validator

Custom Validators

When a constraint cannot be expressed declaratively, write it:

@field_validator("username")
@classmethod
def no_spaces(cls, v: str) -> str:
    if " " in v:
        raise ValueError("username cannot contain spaces")
    return v.lower()          # validators can normalise, not just check

Note that it returns the value. A field_validator is a transformation step, which makes it the right place to strip whitespace, lowercase emails, or round money.

For rules spanning several fields — "end date must be after start date" — use @model_validator(mode="after"), which runs once the whole object exists.

Settings from the Environment

pydantic-settings applies the same machinery to configuration, so a missing environment variable fails at startup with a clear message instead of at 3am with an AttributeError:

class Settings(BaseSettings):
    database_url: str
    port: int = 8000
    model_config = SettingsConfigDict(env_file=".env")

Code Example #1 (Basic)

Validation, coercion, and readable errors.

from datetime import date
from pydantic import BaseModel, EmailStr, Field, ValidationError, field_validator


class Customer(BaseModel):
    id: int
    email: EmailStr
    full_name: str = Field(min_length=2, max_length=80)
    age: int = Field(ge=18, le=120, description="Must be an adult")
    signup_date: date
    tags: list[str] = Field(default_factory=list)     # NOT default=[]
    balance: float = 0.0

    @field_validator("full_name")
    @classmethod
    def tidy_name(cls, v: str) -> str:
        return " ".join(v.split()).title()            # normalise, then return


# --- Valid input, including type coercion from strings ---
good = Customer(
    id="1042",                       # str -> int, automatically
    email="ADA@example.com",
    full_name="  ada   lovelace  ",  # tidied by the validator
    age="36",
    signup_date="2024-03-11",        # str -> datetime.date
    tags=["premium", "beta"],
)
print(good.model_dump())
print(f"id is {type(good.id).__name__}, signup_date is {type(good.signup_date).__name__}\n")

# --- Invalid input: every problem reported at once ---
try:
    Customer(
        id="not-a-number",
        email="missing-at-sign",
        full_name="X",
        age=12,
        signup_date="11/03/2024",
    )
except ValidationError as exc:
    print(f"{len(exc.errors())} validation errors:")
    for err in exc.errors():
        field = ".".join(str(p) for p in err["loc"])
        print(f"  {field:<14} {err['msg']}")

# --- Serialise back out ---
print("\nJSON:", good.model_dump_json(indent=None)[:90], "...")
print("Excluding fields:", good.model_dump(exclude={"balance", "tags"}))

The error loop is what makes Pydantic usable in an API. exc.errors() returns a list of dicts with loc, msg, and type — structured enough to return straight to a client as JSON, which is exactly what FastAPI does.

Code Example #2 (Intermediate)

Nested models, cross-field rules, aliases, and typed settings.

from datetime import date, datetime
from decimal import Decimal
from enum import Enum
from typing import Annotated, Literal

from pydantic import (BaseModel, ConfigDict, Field, ValidationError,
                      computed_field, field_validator, model_validator)


class Status(str, Enum):
    PENDING = "pending"
    SHIPPED = "shipped"
    CANCELLED = "cancelled"


Money = Annotated[Decimal, Field(ge=0, decimal_places=2)]


class Address(BaseModel):
    line1: str = Field(min_length=1)
    city: str
    postcode: str = Field(pattern=r"^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$")
    country: Literal["GB", "IE"] = "GB"

    @field_validator("postcode")
    @classmethod
    def upper(cls, v: str) -> str:
        return v.upper().strip()


class OrderLine(BaseModel):
    sku: str = Field(pattern=r"^[A-Z]{3}-\d{4}$")
    quantity: int = Field(gt=0, le=999)
    unit_price: Money

    @computed_field                       # derived, appears in model_dump()
    @property
    def line_total(self) -> Decimal:
        return (self.unit_price * self.quantity).quantize(Decimal("0.01"))


class Order(BaseModel):
    # forbid: reject unknown keys instead of silently ignoring them
    model_config = ConfigDict(extra="forbid", populate_by_name=True)

    order_id: int = Field(alias="orderId")            # JSON is camelCase...
    placed_at: datetime = Field(alias="placedAt")     # ...Python stays snake_case
    status: Status = Status.PENDING
    ship_to: Address = Field(alias="shipTo")
    lines: list[OrderLine] = Field(min_length=1)
    promised_by: date | None = Field(default=None, alias="promisedBy")

    @computed_field
    @property
    def total(self) -> Decimal:
        return sum((line.line_total for line in self.lines), Decimal("0.00"))

    @model_validator(mode="after")
    def check_consistency(self):
        # Cross-field rules need the whole object, so mode="after"
        if self.promised_by and self.promised_by < self.placed_at.date():
            raise ValueError("promisedBy cannot be before placedAt")
        if self.status is Status.CANCELLED and self.total > 0:
            skus = {line.sku for line in self.lines}
            raise ValueError(f"cancelled order still has billable lines: {sorted(skus)}")
        duplicates = {line.sku for line in self.lines
                      if sum(l.sku == line.sku for l in self.lines) > 1}
        if duplicates:
            raise ValueError(f"duplicate SKUs: {sorted(duplicates)}")
        return self                        # must return self


payload = {
    "orderId": 88213,
    "placedAt": "2024-05-02T14:31:00Z",
    "shipTo": {"line1": "12 Kirkgate", "city": "Leeds", "postcode": "ls1 6dg"},
    "lines": [
        {"sku": "WGT-0042", "quantity": 3, "unit_price": "19.99"},
        {"sku": "GDT-1180", "quantity": 1, "unit_price": "245.00"},
    ],
    "promisedBy": "2024-05-09",
}

order = Order.model_validate(payload)
print(f"order {order.order_id}  status={order.status.value}  total={order.total}")
print(f"postcode normalised to: {order.ship_to.postcode}")
for line in order.lines:
    print(f"  {line.sku}  x{line.quantity}  @ {line.unit_price}  = {line.line_total}")

# by_alias=True round-trips back to the camelCase the API speaks
print("\nback to JSON:", order.model_dump_json(by_alias=True)[:120], "...")

# --- Failures: nested paths and cross-field rules ---
bad = {
    "orderId": 5,
    "placedAt": "2024-05-02T14:31:00Z",
    "shipTo": {"line1": "", "city": "Leeds", "postcode": "NOPE"},
    "lines": [{"sku": "bad-sku", "quantity": 0, "unit_price": "-3"}],
    "promisedBy": "2024-04-01",
    "extraField": "unexpected",
}
try:
    Order.model_validate(bad)
except ValidationError as exc:
    print(f"\n{len(exc.errors())} errors, each with a full path:")
    for err in exc.errors():
        print(f"  {'.'.join(str(p) for p in err['loc']):<22} {err['msg']}")

# --- The schema FastAPI turns into OpenAPI docs, for free ---
schema = Order.model_json_schema()
print("\nrequired fields:", schema["required"])
print("nested definitions:", sorted(schema.get("$defs", {}).keys()))

Three production details worth stealing: extra="forbid" turns a typo'd JSON key into a loud error rather than a silently ignored field; alias lets the wire format be camelCase while your Python stays idiomatic; and Decimal — never float — for money, because 0.1 + 0.2 is not 0.3 and an invoice must balance.


Common Mistakes

  1. Using Field(default=[]): one list shared by every instance, the classic mutable-default bug. Use default_factory=list.
  2. Mixing v1 and v2 method names: .dict() and @validator still work but are deprecated. Use .model_dump() and @field_validator.
  3. Forgetting @classmethod under @field_validator: raises a confusing signature error at class definition time.
  4. A validator that checks but does not return: the field silently becomes None. Always return v.
  5. Cross-field logic in a field_validator: the other fields may not be parsed yet. Use @model_validator(mode="after").
  6. Leaving extra at the default: unknown keys are ignored, so {"emial": ...} passes validation and the real field takes its default. Set extra="forbid" on anything crossing a network boundary.
  7. float for money: use Decimal with decimal_places=2.
  8. Catching ValidationError and re-raising a bare string: you throw away the structured loc/msg list that makes the error actionable.
  9. Not installing email-validator: EmailStr raises an import error rather than a validation error.
  10. Treating Pydantic as an ORM: it validates data shapes. Use SQLAlchemy for persistence, and a separate Pydantic model for the API layer.
  11. One model for input, output, and storage: the API should not accept id or created_at from the client. Separate OrderCreate from OrderRead.

Best Practices

  • Validate once at the boundary, then trust the typed object everywhere inside. That is the whole value proposition.
  • Set extra="forbid" on every model that parses external input.
  • Use Decimal for money and datetime/date for time — never strings or floats.
  • Separate request and response models: UserCreate (accepts a password) and UserRead (never returns one).
  • Prefer declarative Field constraints over custom validators; reach for @field_validator only when the rule cannot be expressed as a constraint.
  • Normalise inside validators — lowercase emails, strip whitespace, uppercase postcodes — so downstream code never has to.
  • Use Annotated types for reusable constraints (Money, Postcode) instead of repeating Field(...) in ten places.
  • Use alias plus populate_by_name when the wire format does not match Python conventions.
  • Return exc.errors() to API clients, not str(exc) — the structured list tells them exactly which field failed.
  • Put configuration in BaseSettings so a missing environment variable fails loudly at startup.
  • Use Enum and Literal for closed sets so invalid states are unrepresentable rather than merely unlikely.

Practice Exercises

  1. The Strict Model: Build a BookOrder model with an ISBN matching a regex, a quantity between 1 and 50, a Decimal price, and extra="forbid". Feed it three bad payloads and print the full loc/msg for every error.
  2. The Cross-Field Rule: Create a Booking model with check_in and check_out dates and a @model_validator(mode="after") enforcing that check-out is at least one day later. Show it accepting a valid booking and rejecting an invalid one.
  3. The Alias Round-Trip: Define a model whose JSON uses camelCase and whose Python attributes use snake_case, parse a camelCase payload, then serialise it back with by_alias=True and confirm the output matches the input exactly.