Request/Response Validation with Pydantic
Validate payloads with Pydantic models to fail fast on bad inputs.
In plain words
Validation checks that the information sent to your model makes sense, such as realistic ages and known categories, and returns a clear message when it doesn't.
Think of it like…
A pharmacy intake form. The pharmacist won't dispense on a prescription with an impossible dose or an unknown drug code; the form says exactly which fields are required and what values are valid, and a pattern of bad forms from one clinic tells the pharmacy something is wrong at that clinic.
Where you’ve seen it
The churn contract is a Pydantic model: tenure_months: int = Field(ge=0, le=600), monthly_charges: float = Field(ge=0, le=10_000), contract: Literal["month", "year", "two_year"], has_streaming: bool, region: str = Field(min_length=2, max_length=2) and model_config = ConfigDict(extra="forbid"). The same class lives in a shared contracts package imported by the API and by the training code's data checks, so the ranges the model saw in training and the ones enforced in serving can't drift apart. A request with tenure_months: 12, monthly_charges: "59.9" passes because lax mode coerces the numeric string, while money fields use strict mode in the payments-facing service where a string must be rejected. A payload with contract: "weekly" (a new plan launched upstream) is not silently mapped: the API returns 422 with loc: ["body", "contract"], and a counter validation_errors_total{field="contract"} rises. The policy matrix is explicit: reject impossible values (negative tenure), impute with the training median and flag documented optional fields (a missing monthly_charges gets imputed_fields: ["monthly_charges"] in the response), and map unknown categories to other only for features where training included an other bucket. Of 1,000,000 daily requests, 3,000 (0.3%) are rejected; the dashboard breaks failures down by field and client, and a sudden jump to 2% on monthly_charges led to a partner sending cents instead of dollars, caught within an hour. Batch scoring validates a 1,000-row DataFrame with pandera or a list of Pydantic models and returns a per-row error report with row indices rather than failing the whole file. Validation overhead is tens of microseconds per request, negligible against 8 ms of inference. Sensitive values are never echoed in error messages or logs; only field paths and error types are kept.
Words you’ll hear
- Feature contract
- The documented types, ranges and categories a model expects as input.
- 422 Unprocessable Content
- Status for well-formed JSON that violates the schema.
- Strict mode
- Validation that refuses type conversion, such as a string where a number is required.
- Unseen category
- A category value that never appeared in the training data.
Visual diagram
Theory & deep dive
Writing the feature contract
Turn what you know about the training data into constraints. Types (int, float, bool, datetime), ranges (ge, le, gt, lt), lengths and patterns for strings (min_length, max_length, pattern), allowed values (Literal["month", "year", "two_year"] or an Enum), required versus optional fields with explicit defaults and nested structures (a list of recent orders). Set extra="forbid" so misspelled or unexpected fields fail loudly. Derive ranges from the training data but allow for legitimate growth: the minimum and maximum of a feature in the training set are not necessarily its valid range, so combine data profiling with domain limits (a tenure of 600 months is already generous).
Distinguish validity from plausibility. Validity is a hard contract (negative tenure is impossible and is rejected). Plausibility is statistical (a monthly charge of $9,000 is valid but extreme): accept it, flag it (out_of_training_range: ["monthly_charges"]) and count it, because extrapolation is where models fail. Keep the contract in one shared package, version it with the model and generate the JSON Schema and API docs from it, so training-time data checks, serving validation and client SDKs all agree.
Request {"tenure_months": -3, "monthly_charges": 59.9, "contract": "weekly"} → 422 with errors: tenure_months Input should be greater than or equal to 0; contract Input should be 'month', 'year' or 'two_year'. No model call is made.
Policies for bad, missing and unseen values
For each feature choose a policy and document it. Reject values that are impossible or that the model cannot interpret. Coerce harmless formatting differences (a numeric string) in lax mode, but use strict types where exactness matters (money, IDs). Impute documented optional fields with the same value used in training (the training median or a missing-indicator pair) and report the imputation in the response, since silently different imputation between training and serving is a classic source of skew. Unseen categories are the most common production surprise: map to an other bucket only if training included one (and the encoder handles it); otherwise reject or route to a fallback rule, because a one-hot encoder with handle_unknown="ignore" quietly scores the row as if the category were absent.
Make validation a monitoring signal. Count rejections by field, client and error type: a baseline of 0.3% (3,000 of 1,000,000 daily requests) that jumps to 2% on monthly_charges points to an upstream change (cents instead of dollars), a new category points to a product launch the model hasn't seen. Alert on rate changes, and feed out-of-range counts into drift dashboards. For batch inputs, validate a DataFrame with pandera or a list of Pydantic models and return a per-row report (row index, field, reason) while still scoring the valid rows, rather than failing a 100,000-row file for one bad record. Keep validation cheap (tens of microseconds per request compared with 8 ms of inference), and never echo sensitive values in errors or logs.
tenure_months: reject if < 0 · monthly_charges: impute training median 64.2 if missing, flag if > training p99.9 · contract: reject unseen · region: map unknown to "ZZ" only if training had an other bucket · extra fields: reject.
How it works, step by step
Step 1 of 41. Profile training data
Record types, ranges, categories and missing rates, then combine them with domain limits to draft the contract.
- Include
- other buckets
When to use it & trade-offs
What it is
A prediction service must decide what to do with bad inputs before they reach the model. Pydantic lets you encode the feature contract in code: field types, allowed ranges, categorical values (Literal or Enum), required versus optional fields and nested structures. A request that violates the contract is rejected with a precise 422 error listing the offending fields; a valid request becomes a typed object. The response model does the same for output (score, label, model version, request ID), so clients get a stable schema. For data scientists the interesting questions are the policy choices: reject, coerce or impute a bad value; how to treat unseen categories, out-of-range values and missing features; and how validation failures themselves become a monitoring signal for upstream data problems and drift.
Why it matters: A model silently scoring garbage is worse than an error. An age of 250 or a monthly charge of −40 produces a number that looks plausible to the caller, a unit mix-up (dollars versus cents) shifts every score and a new category name from an upstream system can fall into an unintended bucket. Because models are trained on data with certain ranges and categories, the serving contract should state them explicitly, keep training and serving consistent and surface violations early instead of letting them poison decisions and dashboards.
When to reach for it
- Shared contract between training data checks and the API
- Per-feature reject, impute or map policies
- Validation-failure rates as a data-quality signal
When to avoid or be careful
- Letting unknown categories flow silently into one-hot encoders
- Different imputation in serving than in training
- Echoing sensitive input values in error messages
Handling a bad value
Strengths: Safe; makes upstream bugs visible.
Watch out: The caller gets no score.
Strengths: Still returns a prediction.
Watch out: Must match training exactly; hides data gaps if unflagged.
Strengths: Graceful degradation.
Watch out: Can mask new important categories.
Interview signals & numbers to know
When this topic comes up
- “What if the API receives a category the model never saw?”
- Validity versus plausibility
- Strict versus lax validation
- Using rejection rates for monitoring
- Batch validation with row-level reports
Benchmarks & rules of thumb
- 0.3%
- baseline rejection rate in the example (3,000 of 1M daily requests)
- tens of µs
- validation overhead against 8 ms of inference
- 422
- status for schema violations on well-formed requests
Common mistakes & follow-ups
Common interview mistakes
- Setting ranges from the training minimum and maximum without domain limits.
- Using handle_unknown=ignore and never noticing new categories.
- Rejecting a whole batch file for one invalid row.
Likely interviewer follow-ups
- How would you detect an upstream unit change?
- How do you keep the training and serving schemas identical?
- When is imputing at serving time acceptable?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Request/Response Validation with Pydantic with data science interview Q&A and hands-on practice.