Python, properly · Chapter 34 of 42
Pydantic
By the end of this chapter you can describe data as Pydantic models, validate JSON, CSV rows and API responses against them, turn validation errors into clear messages, clean messy input with validators, and read settings from the environment. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Pythonic and typed
- 5 tasks
- Python
- In the all labs plan
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.
Why you need this
Every byte DabbaDrop's code reads comes from outside: menu.json that Bhavna edits by hand, the API's JSON, the CSV export with Rs 240 in the totals, and soon the replies of an AI model. Last chapter's hints describe that data, but nothing checks it when the program runs: a price of "free" would sail through until a bill crashed.
Pydantic reads the same type hints and checks the data at run time. Data that fits becomes a typed object; data that does not is refused with a precise report. It is the most used validation library in Python, and the base of FastAPI, the OpenAI and Anthropic SDKs, LangChain and Pydantic AI: when an AI framework asks a model for structured output or calls your tool, a Pydantic model is what checks the JSON.
What you build: 5 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
dish_model.py: a validated menu
Write a Pydantic model Dish for one dish of menu.json: id (text), name (text, at least one character), category (exactly veg, non-veg or jain), price (a whole number of rupees, more than 0), spice (a whole number from 0 to 3) and available (true or false, True when missing). Then load_menu(path): the list of Dish read from that JSON file.
The check loads the real menu (all 24 dishes must load and match the file), then tries bad dishes: a price of -5 or 0, the category vegan, a spice of 4 or -1, an empty name, no price at all. Each must raise a ValidationError about that field.
- Task 2
api_models.py: the API's orders
GET /orders on DabbaDrop's API answers with a page: orders (a list), page, per_page, total and next (null on the last page). Look at one order with curl localhost:8000/orders/D0001. Write two models:
Order: id, customer_id, items (dish id to quantity), total, status (placed, cooking, out_for_delivery, delivered or cancelled), placed_at and delivered_at (datetimes; delivered_at is null until delivered), rider_id (text or null), payment (upi, cash or card);
OrdersPage: orders (a list of Order), page, per_page, total and next.
Then parse_page(text): an OrdersPage from the JSON text. The check parses real pages and orders: placed_at must be a datetime still at +05:30. A status of lost, a payment of gpay, a placed_at of yesterday, a quantity of two, or an order with no rider_id key at all must be rejected.
- Task 3
csv_order.py: cleaning the CSV export
Write a model CsvOrder for one row of /workspace/data/orders.csv as csv.DictReader gives it (every value is text), cleaning as it validates:
order_id, customer_id and payment as they are; items like roti:2;dal-tadka:1 becomes the dict roti 2, dal-tadka 1; total 240, Rs 240 and ₹240 all become 240; status in lower case; placed_at a datetime; delivered_at a datetime, or None when the cell is blank; rider_id and coupon text, or None when blank.
Then read_orders(path): every row as a CsvOrder. The check reads all 601 rows and compares every field, and a total of Rs two hundred must still be rejected.
- Task 4 · interview question
Interview: new_order.py, friendly validation errors
Write a model NewOrder: customer_id (C followed by exactly three digits, like C012), items (dish id to quantity, at least one dish, every quantity a whole number of at least 1), payment (upi, cash or card; upi when missing).
Then errors_for(data): validate the dict as a NewOrder and return every problem as one line, field then a colon and a space then Pydantic's own message, or an empty list when it is valid. The field is the error's location joined with dots, so a quantity of 0 for roti gives items.roti: Input should be greater than 0. An empty dict gives two lines, one per missing field.
- Task 5
settings.py: settings from the environment
Write Settings with pydantic-settings, reading environment variables that start with DABBA_: api_url (text, http://localhost:8000 when DABBA_API_URL is not set), api_key (a secret that is never shown when printed, required, from DABBA_API_KEY) and timeout (seconds as a float, 5.0 when DABBA_TIMEOUT is not set).
The check sets the variables and runs Settings(): with DABBA_TIMEOUT=2.5 the timeout is 2.5, api_key's secret value is the key but printing the settings does not show it, a timeout of soon is rejected, and without DABBA_API_KEY Settings() raises a ValidationError.
What you will learn
- Models: classes of typed fields, with defaults.
- Validation and coercion, and reading a ValidationError.
- Constraints: Field(...), Literal, nested models, X | None.
- Parsing JSON (model_validate_json, TypeAdapter), validators for messy input, and output (model_dump, JSON Schema).
- Settings with pydantic-settings.
More in Pythonic and typed
Build "Pydantic" yourself
DabbaDrop, a Mumbai tiffin startup, runs on Excel and WhatsApp. You are its first Python developer. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
The first 2 chapters of Python, properly are free. This one comes with the all labs plan.