Learning path: Data and Features in Production · Step 5 of 8
Data Validation and Schema Checks: Stop Bad Input Before It Reaches the Model
Send messy input to a car price API and it still answers, with a wrong price. Add a Pydantic schema that refuses impossible values with a 422, a four-rule batch check before training, and see why a valid value can still be wrong.
What you will learn
- See why a model API answers messy input with a calm, wrong number instead of an error
- Put a Pydantic schema with field limits, known categories and extra=forbid in front of a FastAPI model
- Check a training file with four plain pandas rules before any fit
- Explain why a valid value can still be wrong, and what helps
Before you start
- Deploy a Machine Learning Model with FastAPI
- FastAPI Request and Response Models with Pydantic
- Pipelines and ColumnTransformer
Imagine you're posting a parcel. The clerk at the counter takes a complete form: address filled in, under the weight limit, stamp on. Off it goes. Someone else brings a parcel with no address that weighs 40 kilos. It's sent back on the spot, and they're told why.
And this one? The form is perfect and says house 12. You meant house 21. Every check passes, and it goes to the wrong house.
The counter is your schema. The wrong house is a value that's valid, and still wrong. The clerk checks the form, not the truth. Keep both halves of that in mind for this lesson.
The project
A small car price model behind FastAPI: five inputs (enginesize in cubic inches, curbweight in pounds, horsepower, brand, carbody) and one price, trained on CarPrice.csv with a random forest. Training prints 164 train, 41 test and a test RMSE of 2068. Each script calls the API with FastAPI's TestClient, so no server has to run. If serving a model with FastAPI is new, start with Deploy a Machine Learning Model with FastAPI.
AUDI = {"enginesize": 131, "curbweight": 3053, "horsepower": 160,
"brand": "audi", "carbody": "hatchback"}
TRIES = [("right values", {}),
("weight in kg", {"curbweight": 1385}),
("engine in litres", {"enginesize": 2.1}),
("brand in capitals", {"brand": "AUDI"}),
("horsepower -5", {"horsepower": -5}),
("horsepower null", {"horsepower": None}),
("horsepower text", {"horsepower": "a lot"})]
Messy input, and it still answers
First, no checks at all. The API takes a plain dictionary and hands it to the model:
@app.post("/price")
def price(car: dict):
row = pd.DataFrame([car])
return {"price": round(float(model.predict(row)[0]))}
right values 200 {"price":19091}
weight in kg 200 {"price":7802}
engine in litres 200 {"price":14876}
brand in capitals 200 {"price":18058}
horsepower -5 200 {"price":16349}
horsepower null 200 {"price":17811}
horsepower text 500 Internal Server Error
The Audi with the right values comes back at 19,091. The same car with its weight in kilograms: status 200 and 7,802, less than half. Engine size in litres: 14,876. Minus five horsepower: 200. A null horsepower: also 200. Only plain text crashed it, with a 500 that doesn't tell the caller why.
A crash, you notice. A wrong price, you don't.
Why nothing complained
def make_model():
cat_lane = make_pipeline(
SimpleImputer(strategy="most_frequent"),
OneHotEncoder(handle_unknown="ignore"))
prepare = ColumnTransformer([
("num", SimpleImputer(strategy="median"), NUM),
("cat", cat_lane, CAT)])
forest = RandomForestRegressor(random_state=42)
return make_pipeline(prepare, forest)
- The imputer sees a null and fills in the median, 95. No warning, because that's the job we gave it.
- The encoder has one cell per brand, 22 of them.
audilights up one cell.AUDIlights up none, because ofhandle_unknown="ignore". All zeros, no error. - The forest only knows the weights it trained on. 1,385 is lighter than all of them, and so is 1. A car weighing one pound gets the same price, 7,802.
Every step did its job. Nobody asked it to say no. A model always gives a number. It never says "I don't know".
Pydantic at the door
So let's ask it to say no. The limits live in one dictionary:
LIMITS = {"enginesize": (50, 400), # cubic inches
"curbweight": (1000, 6000), # pounds
"horsepower": (40, 400),
"price": (1000, 200000)}
from pydantic import BaseModel, ConfigDict, Field, field_validator
def within(col):
low, high = LIMITS[col]
return Field(ge=low, le=high)
class Car(BaseModel):
model_config = ConfigDict(extra="forbid")
enginesize: float = within("enginesize")
curbweight: float = within("curbweight")
horsepower: float = within("horsepower")
brand: str
carbody: str
@field_validator("brand")
def known_brand(cls, value):
if value not in BRANDS:
raise ValueError(f"unknown brand {value!r}")
return value
@field_validator("carbody")
def known_body(cls, value):
if value not in BODIES:
raise ValueError(f"unknown body {value!r}")
return value
@app.post("/price")
def price(car: Car):
row = pd.DataFrame([car.model_dump()])
return {"price": round(float(model.predict(row)[0]))}
- Each number must be a float, and
withinturns a pair of limits into a field rule. - The brand and body are checked against known lists, with a clear error for an unknown one.
extra="forbid"refuses a field we don't know about.- One word changes in the route:
car: dictbecomescar: Car, and FastAPI runs the schema before any of our code.
(To shape those refusals into one short 422 and add health checks around the model, see A Production FastAPI for an ML Model. Here we stay on what the checks can and can't catch.)
A clear 422, before the model is touched
right values 200 {"price":19091}
weight in kg 200 {"price":7802}
engine in litres 422 enginesize: Input should be greater than or equal to 50
brand in capitals 422 brand: Value error, unknown brand 'AUDI'
horsepower -5 422 horsepower: Input should be greater than or equal to 40
horsepower null 422 horsepower: Input should be a valid number
horsepower text 422 horsepower: Input should be a valid number, unable to parse string as a number
field missing 422 carbody: Field required
horsepower "160" 200 {"price":19091}
The text "160" passes, because Pydantic can turn it into a number safely. A 422 never touches the model. But one line still says 200 and 7,802: the weight in kilograms. We'll come back to it.
Check the delivery before training
The API is one door. Your training data is the other. Here is a batch check in plain pandas, no new package, with four rules:
import pandas as pd
from cars import LIMITS, NEEDED
MAX_NULL = 0.05
def check_cars(df):
problems = []
missing = [c for c in NEEDED if c not in df.columns]
if missing:
problems.append(f"missing columns: {missing}")
for col in [c for c in NEEDED if c in df.columns]:
share = df[col].isna().mean()
if share > MAX_NULL:
problems.append(f"{col}: {share:.0%} null")
if col not in LIMITS:
continue
if not pd.api.types.is_numeric_dtype(df[col]):
problems.append(f"{col}: not a number")
continue
low, high = LIMITS[col]
bad = ((df[col] < low) | (df[col] > high)).sum()
if bad:
problems.append(f"{col}: {bad} outside {low}-{high}")
return problems
- Are the required columns there?
- Is any column more than 5% empty?
- Is a number column really a number?
- Are the values inside the same limits as the schema?
clean file: 205 rows, 0 problems
damaged file: 205 rows
- missing columns: ['carbody']
- curbweight: 5 outside 1000-6000
- horsepower: not a number
- price: 15% null
On a copy we damaged on purpose, it reports all four problems at once. train.py calls check_cars first and stops before training if the list isn't empty.
Why bother? We damaged the training rows quietly (a third of the engine sizes in litres, a fifth of the horsepower blank) and skipped the check:
clean training: RMSE 2068
damaged training: no error, RMSE 2404
check would say: ['enginesize: 49 outside 50-400', 'horsepower: 23% null']
Training gives no error at all, and test RMSE goes from 2,068 to 2,404. It isn't guaranteed: over 20 splits it got worse in 16 and better in 4. The check would have caught both problems before any fit.
A value can be valid, and still wrong
right values 200 {"price":19091}
weight in kg 200 {"price":7802}
weight mistyped 200 {"price":7996}
engine mistyped 200 {"price":15886}
limit 1819-4066: refuses 41 of 41 cars in kg, and 2 honest cars in pounds
1,385 is well inside the 1,000 to 6,000 limit, so the schema is happy. Mistyped values pass too: a weight of 2,053 instead of 3,053, an engine of 113 instead of 131. Four times 200. A check reads the shape of a value, not what you meant.
Tighten the limit to the weights we trained on (1,819 to 4,066)? It refuses all 41 test cars sent in kilos, but also refuses 2 honest cars in pounds, and the typos still get through. That's a trade-off. What helps:
- Put the unit in the name (for example a field called weight in pounds), so the caller can't miss it.
- Send one known car through the API and compare the price with the one you expect.
- Watch incoming values against your training data.
One feature, computed two ways
One more look. Training reads the weight from the file, in pounds. Suppose the serving side has a small helper that works in kilos: same column name, computed a different way.
def training_features(cars):
return cars # pounds, as in the file
def serving_features(cars):
out = cars.copy() # a helper, in kilos
out["curbweight"] = (out["curbweight"] * 0.4536).round()
return out
training way: RMSE 2068, R2 0.95
serving way: RMSE 5067, R2 0.67
pass the schema: 30 of 41
Test RMSE goes from 2,068 to 5,067, and it more than doubled in all 20 splits tried. 30 of the 41 cars would pass the schema anyway. Same name, two meanings: that's training-serving skew, and it has its own lesson in Training-Serving Skew.
Common mistakes
- Taking
dictin a model route. Anything goes straight to the model. - Trusting imputers and
handle_unknown="ignore"at serving time. They hide bad input instead of refusing it. - Training without a batch check. Damage trains without an error.
- Thinking a schema proves the data is right. It only proves the data is possible.
Quick recap
| Guard | Catches | Misses |
|---|---|---|
| No checks | Only plain text (500) | Kilos, litres, negatives, nulls: all 200 |
| Pydantic schema | 6 of 9 requests, 422 with the field name | Kilos and typos inside the limits |
| Batch check before training | Missing column, nulls, text, out of range | Plausible wrong values |
Try it yourself
Add a car with horsepower 500 to tries.py and run both scripts. Then raise the limit in cars.py and run the schema one again.
The project and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Point-in-Time Correctness: Join Features as of Each Event with merge_asof
Next →Training-Serving Skew: Same Model, Different Inputs, and How to Detect It
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.