Input Validation with Pydantic
Typed schemas that validate API payloads and structured LLM outputs.
In plain words
Pydantic checks that the data you receive looks like what you expected, with the right types and sensible limits, and tells you precisely what is wrong when it doesn't.
Think of it like…
A customs checkpoint with a form. Each declared item must match the rules (type, size, allowed categories); incomplete or odd paperwork is stopped at the border with a note saying exactly which box is wrong, rather than being discovered inside the country.
Where you’ve seen it
The chat endpoint defines class Message(BaseModel) with role: Literal["user", "assistant"] and content: str = Field(min_length=1, max_length=20_000), and class ChatRequest(BaseModel) with model_config = ConfigDict(extra="forbid"), messages: list[Message] = Field(min_length=1, max_length=50), temperature: float = Field(0.2, ge=0, le=2) and max_tokens: int = Field(512, ge=1, le=4096). The 20,000-character cap bounds a prompt to about 5,000 tokens (at roughly 4 characters per token), so input cost per message is at most 5,000 × $2.50 / 1,000,000 = $0.0125 on the large model; without it one request could carry a million characters. With extra="forbid", a typo such as temprature returns 422 with loc: ["body", "temprature"] instead of being silently ignored. A request with temperature: 7 returns {"detail": [{"loc": ["body", "temperature"], "msg": "Input should be less than or equal to 2", "type": "less_than_equal"}]}. Output validation is just as important. The model is asked for a TicketSummary (title, severity as an enum, confidence: float from 0 to 1, tags list) and the response is passed to TicketSummary.model_validate_json(...). About 6% of first attempts fail validation (trailing prose, a severity of "urgent" that isn't in the enum); the service sends the validation errors back to the model for one repair attempt, which succeeds on about 83% of those failures, lifting overall validity to 0.94 + 0.06 × 0.83 ≈ 99.0%, at the cost of extra model calls on 6% of requests. Tool calls get the same treatment: the model proposes refund(order_id, amount); a RefundArgs model checks that order_id matches the tenant's orders, amount is positive and below a policy ceiling and only then does the code run, so a manipulated or hallucinated argument can't trigger a harmful action. Strict mode is used for money fields so that "10" isn't coerced into 10. Validation errors are logged with the field paths but never with the raw sensitive values.
Words you’ll hear
- BaseModel
- A Pydantic class whose typed fields define and enforce a data schema.
- Coercion
- Converting compatible input, such as "5" to 5, in lax mode.
- Strict mode
- Validation that rejects values needing type conversion.
- Repair loop
- Sending validation errors back to a model so it can correct its output.
Visual diagram
Theory & deep dive
Models, constraints and coercion
A Pydantic v2 model declares the schema once: class ChatRequest(BaseModel): messages: list[Message] = Field(min_length=1, max_length=50). Constraints attach through Field (ge, le, min_length, max_length, pattern) or through Annotated types, Literal and Enum restrict values to a known set, nested models validate structured payloads and discriminated unions select among variants by a tag field (for example type: "text" | "image"). field_validator and model_validator add custom rules (a start date before an end date). Set model_config = ConfigDict(extra="forbid") so unknown fields raise errors instead of being ignored, which catches typos like temprature and blocks parameter smuggling.
Coercion is the default (lax) behaviour: "5" becomes 5, "true" becomes True. It is convenient for query strings and forms but dangerous for money or IDs, so use strict mode or strict field types where exactness matters. Errors are structured: each has loc (a path such as ["body", "temperature"]), msg and type, so an API can return 422 with field-level detail that clients can display. FastAPI wires this up automatically for request bodies, query parameters and response models, and generates OpenAPI and JSON Schema from the same models. Keep validation at the boundary and use typed objects internally.
Body {"messages": [], "temperature": 7, "temprature": 1} → three errors: messages too short (min_length 1), temperature greater than 2 and temprature extra field not permitted. All reported at once with their loc paths.
Validating LLM output and tool calls
Model output is untrusted input: it may contain prose around the JSON, a missing field, the wrong type or an enum value you didn't offer. Use the provider's structured output or JSON-schema mode where available (generate the schema from the Pydantic model with model_json_schema()), then still run Model.model_validate_json(text), since schema-constrained decoding reduces but doesn't eliminate problems and business rules (a confidence between 0 and 1, severity in an enum) need checking. On ValidationError use a repair loop: send the original request plus the error messages back to the model for one or two retries, then fall back to a default or a human queue. With a 6% first-attempt failure rate and an 83% repair success rate on those failures, validity rises from 94% to 0.94 + 0.06 × 0.83 ≈ 99.0%, at the cost of extra calls on 6% of requests.
Tool-call arguments deserve the strictest validation, because they trigger actions: validate types and ranges (amount positive, below a ceiling), ownership (the order_id belongs to the caller's tenant), allow-lists (known tools, known recipients) and sizes, before executing. This is a key defence against prompt injection and hallucinated arguments, though not a substitute for authorisation checks and human approval of risky actions. Also bound input size on requests: a max_length of 20,000 characters caps a prompt at about 5,000 tokens, so worst-case input cost per message is 5,000 × $2.50 / 1M = $0.0125. Log which fields failed (paths and error types), not raw sensitive values, and track validation-failure rates for both clients and models, since a rise often reveals a client bug or a prompt regression.
100,000 model outputs: 94,000 valid first time; 6,000 invalid → repair attempt fixes 83% = 4,980. Valid total 98,980 = 98.98%, about 99.0%. Extra calls: 6,000 (6%). Remaining 1,020 go to a fallback or human review.
How it works, step by step
Step 1 of 41. Define request and response models
Write Pydantic models with constraints, extra fields forbidden and sensible length and range caps.
- Use
- strict for money and IDs
When to use it & trade-offs
What it is
Pydantic validates data against Python type annotations. You declare a BaseModel with typed fields and constraints (Field(ge=0, le=2), min_length, max_length, pattern), and Pydantic parses and checks incoming data, coercing compatible values (the string "5" to the integer 5 in default mode, or rejecting them in strict mode) and raising a ValidationError with a list of precise problems (loc, msg, type). FastAPI uses it to turn request bodies into validated objects and returns 422 automatically on failure. In AI backends Pydantic does double duty: it validates API payloads from clients and validates structured output from the model and the arguments of tool calls before your code acts on them.
Why it matters: Everything crossing a boundary is untrusted: clients send malformed JSON, oversized prompts and surprising types, and models return JSON that is almost right (a missing field, a string where a number should be, a hallucinated enum value). Validating at the edge fails fast with a clear message, bounds cost (a 20,000-character prompt limit caps spend), blocks whole classes of bugs and security issues and gives you a single, typed contract that doubles as documentation and JSON Schema for structured-output features.
When to reach for it
- FastAPI request and response models
- Parsing structured outputs from LLMs
- Checking tool-call arguments before execution
When to avoid or be careful
- Accepting unknown fields silently
- Lax coercion for money or identifiers
- Executing tool calls from unvalidated model JSON
Validation approaches
Strengths: Typed, declarative; JSON Schema; clear errors.
Watch out: Python-specific; coercion needs care.
Strengths: Portable across services.
Watch out: No native objects; verbose to write.
Strengths: No dependency.
Watch out: Easy to miss cases; inconsistent errors.
Interview signals & numbers to know
When this topic comes up
- “How do you make sure the LLM's JSON is usable?”
- Strict versus lax mode
- Why forbid extra fields
- Bounding prompt size for cost control
- Validating tool arguments
Benchmarks & rules of thumb
- 20,000 chars ≈ 5,000 tokens
- a prompt cap that bounds input to about $0.0125
- 94% → ≈ 99.0%
- validity with one repair attempt
- 422
- status for well-formed requests that fail validation
Common mistakes & follow-ups
Common interview mistakes
- Trusting model output because the provider promised JSON.
- Leaving size limits off and discovering them on the invoice.
- Logging raw invalid payloads that contain sensitive data.
Likely interviewer follow-ups
- How would you handle a model that keeps returning invalid JSON?
- What's the difference between validation and sanitisation?
- How do you version a request schema?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Input Validation with Pydantic with generative AI interview Q&A and hands-on practice.