Skip to content
Streak:0Loading your progress…Sign in

Module 6 · Lesson 1 of 3

Validation with Pydantic

Runtime-validated models — the backbone of FastAPI and LLM structured outputs. ~25 min

Lesson notes

Coming from TypeScript

TypeScript

const User = z.object({
  email: z.string().email(),
  age: z.number().int().min(13),
  tags: z.array(z.string()).default([]),
});
const user = User.parse(json);

Python

from pydantic import BaseModel, Field, EmailStr

class User(BaseModel):
    email: str
    age: int = Field(ge=13)
    tags: list[str] = []

user = User.model_validate(data)       # raises ValidationError
user.model_dump()                      # -> dict
User.model_json_schema()               # -> JSON Schema (for LLM tools!)

Pydantic is Zod for Python. model_json_schema() is how you turn a model into a tool definition or structured-output schema for an LLM.

Custom validators
from pydantic import BaseModel, field_validator

class Signup(BaseModel):
    username: str

    @field_validator("username")
    @classmethod
    def no_spaces(cls, v: str) -> str:
        if " " in v:
            raise ValueError("username cannot contain spaces")
        return v.lower()

Practice

  1. 1. Validate an order payload

    medium25 XP

    Create Pydantic models LineItem(sku: str, qty: int >= 1, unit_cents: int >= 0) and Order(customer_id: str, items: list[LineItem]) where items must be non-empty and sku is upper-cased by a validator. Add a total_cents property on Order. Write parse_order(data: dict) -> Order | list[str] returning the model, or a list of error field paths like "items.0.qty" on failure.

    Ctrl/⌘ + Enter runs the tests · Esc then Tab leaves the editor