Welcome to Pydantic Academy
Where messy data gets a strict makeover β every field clean, typed, and validated.
Enter The AcademyBefore Pydantic vs After
age: "twenty"
email: null
budget: "lots"age: 20
email: "a@b.com"
budget: 1500Messy Data Breaks Everything
AI outputs and API inputs can arrive in any shape. One missing field or wrong type and everything crashes.
Β Β "name": "Alice",
Β Β "age": "twenty-five", # should be int!
Β Β "budget": None, # should be required!
Β Β "email": "not-valid", # not an email!
}
Pydantic reads your class definition and automatically checks every incoming value. No more silent errors!
Watch Pydantic Catch Errors
Try entering wrong types β Pydantic instantly spots the problem.
Pydantic + AI Structured Outputs
Modern LLMs can return validated JSON matching your Pydantic model β no prompt hacking needed.
Nesting Models Inside Models
Pydantic models can contain other models β they all validate recursively.
User validates Company which validates Address β Pydantic checks the whole tree in one call!
Mission: Fix The Broken Model
Mrs. Pydantic's student model has wrong types. Click each broken field to fix it.
Tap the red broken fields to fix them.
Master Pydantic in 4 steps π©βπ«
From messy dict to fully validated, typed data model.
- 1
Install Pydantic
Pydantic is already included in FastAPI. Or install standalone.
pip install pydantic[email]
- 2
Define your model
Subclass BaseModel and declare fields with Python type hints.
from pydantic import BaseModel, EmailStr class User(BaseModel): name: str age: int email: EmailStr budget: float = 0.0 # with default - 3
Validate incoming data
Pass a dict and Pydantic validates, coerces, and raises clear errors.
# Valid user = User(name="Alice", age="25", email="a@b.com", budget=1500) print(user.age) # β 25 (int, not "25") # Invalid β raises ValidationError User(name="Alice", age="oops", email="bad", budget="lots") - 4
Use with OpenAI
Force the model to return a validated Pydantic object.
from pydantic import BaseModel from openai import OpenAI client = OpenAI() class Recommendation(BaseModel): title: str reason: str score: float response = client.beta.chat.completions.parse( model="gpt-4o-mini", messages=[{"role":"user","content":"Recommend a film"}], response_format=Recommendation, ) rec = response.choices[0].message.parsed print(rec.score) # β always a float β
Chat with the Teacher β¨
Questions about validation errors, field constraints, or complex schemas? Ask away!
You're a Data Guardian now!
Your AI outputs are clean, typed, and validated. Next: learn how to measure whether your AI is actually doing a good job β Evals!
Strict Output Contract
Deliverable: Define one schema and validate model output into typed fields.
Stretch: Add one custom validator for a business rule.
Complete the deliverable first, then unlock the stretch goal.