Schema validation: Zod and Pydantic
Practice this questionOverview
- Schema validation verifies data shape, types, required fields, and declared constraints at runtime.
- Zod is commonly used in TypeScript; Pydantic serves a similar role in Python.
- These validators check structure, not whether facts are true or actions are permitted.
Why this matters
Type declarations disappear or are not enforced at runtime, while model/provider data arrives from an external trust boundary.
An everyday example
A form checker verifies that the amount field contains a number; an assessor separately checks whether that amount is justified.
A technical example
An enum restricts intent to known routes, and a bounded string prevents a megabyte-long claim ID.
How it works
- Parse untrusted value
- Reject unknown fields/invalid values
- Normalize deliberately
- Run domain checks
- Persist or execute only valid data.
Architecture and flow
Unknown JSON → Zod/Pydantic → domain validation → permitted operation.
The insurance assistant example
An extracted accident date must be valid, within relevant business constraints, and confirmed when ambiguous.
When to use it
API boundaries, structured outputs, tool arguments, provider results, and event payloads.
When to avoid it
Do not approve coverage merely because covered: true is a valid boolean.
Interview answer
“Runtime schemas make data usable by code; business services still verify truth, authorization, and domain rules.”
Benefits, trade-offs, and production considerations
- Keep schemas and types aligned, reject excess properties when appropriate, and avoid silent coercion at sensitive boundaries.
- Repeated invalid output needs bounded retries and a failure path.
import { z } from "zod";
const ClaimDraft = z.object({
policyId: z.string().min(1).max(80),
incidentDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
description: z.string().min(10).max(5000),
}).strict();
// Teaching boundary: raw is externally produced unknown data.
function parseDraft(raw: unknown) {
return ClaimDraft.parse(raw);
}
// A date-shaped string may still be impossible, e.g. 2026-99-99.
// The business service verifies calendar validity, ownership, applicability,
// and approval of the exact draft before submitting it.