STK-23Default Open source
Use Zod or Pydantic to check every input
Parse every request body, query string, webhook, file and structured model answer at the boundary with a schema library. Use Zod in TypeScript or Pydantic in Python.
Review by
2027-04-30
How to do it
Zod 1.0 came out in March 2020, and version 4.6.7 shipped in October 2026. It has about 207 million weekly downloads. Pydantic 1.0 came out in October 2019, and version 2.14.1 shipped in October 2026, with about 243 million weekly downloads. Both are MIT licensed. One schema gives the check, the type and the error message, as accept only known fields asks. The same definition describes a structured answer from a language model. Zod's z.toJSONSchema() and Pydantic's model_json_schema() write JSON Schema draft 2020-12, which the provider SDKs accept, and the reply is checked with the same schema. What to ask the model for is in Ask for output that matches a schema. Choose something else when the framework has its own checks, such as Django forms, or when another schema library is already in use.
Examples
TypeScript example
import { z } from 'zod';
const NewOrder = z.strictObject({ productId: z.string().uuid(), quantity: z.number().int().min(1).max(99) });
app.post('/orders', (req, res) => {
const result = NewOrder.safeParse(req.body);
if (!result.success) return res.status(400).json({ errors: result.error.issues });
res.status(201).json(createOrder(result.data));
});
Python example
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
class NewOrder(BaseModel):
model_config = ConfigDict(extra="forbid")
product_id: UUID
quantity: int = Field(ge=1, le=99)
How to check
Every route handler reads its input through a schema parse call. A test sends each route one unknown field and one wrong type, and gets 400 or 422. Every model call whose answer code reads passes a schema, and a unit test shows an invalid reply fails it.
Sources
Related rules
- STK-20 Use Express for a Node.js server in Software choices
- STK-22 Use FastAPI for a Python API in Software choices
- API-12 Accept only fields you know in API design
- AIF-12 Ask for output that matches a schema in AI features
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/stack/web-frameworks/zod-pydantic">Agent Wranglers software choices playbook</a>. In code you write, add a comment next to it with the same link.