Sub topic 4
Validating input before it reaches the model
This chapter assumes you know basic Python classes, how HTTP and JSON work, and the request and response contract from the previous chapter. Here you will see how the service rejects bad input before the model ever runs.
Why validate at the boundary
A scikit-learn model accepts almost any numeric array. It does not know that a negative petal length makes no sense. Bad input can produce a confident but wrong prediction, or a crash deep inside the library with an unhelpful error.
The API boundary is where untrusted data enters your system. Checking input there gives you three things:
- Wrong types and missing fields fail fast with a clear message.
- Impossible values never reach the model.
- The model code can assume its input is well formed.
Validation with Pydantic
FastAPI uses Pydantic to check request bodies. You describe the shape once as a class, and FastAPI parses and checks every request against it.
from pydantic import BaseModel, Field
class IrisFeatures(BaseModel):
sepal_length: float = Field(gt=0)
sepal_width: float = Field(gt=0)
petal_length: float = Field(gt=0)
petal_width: float = Field(gt=0)Each field has a type, float, and a constraint, gt=0, which means "greater than zero". All four fields are required because none has a default value.
When the endpoint declares features: IrisFeatures, FastAPI does this before your function body runs:
- Reads the JSON body.
- Converts values to the declared types where it safely can. The string
"5.1"becomes the float5.1. - Checks every constraint.
- Returns an error response if anything fails. Otherwise it calls your function.
What a failure looks like
Send a negative value and the service answers with status 422, which means "Unprocessable Entity". The body lists each problem and its location.
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{"sepal_length": -1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}'The response contains a detail list. Each entry has a loc (here body, then sepal_length), a msg such as "Input should be greater than 0", and a type. A client developer can use this to fix the call without reading your code.
Common errors
- Forgetting constraints. A type alone allows
-5.0,0, and1e308. Addgt,ge,lt, orlewhere the domain has limits. - Using
0as a default for a missing field. A default hides the client's mistake and feeds the model made-up data. Leave required fields without defaults. - Expecting validation to catch unusual but legal values. A petal length of 500 passes
gt=0. If you know a realistic upper bound, addle. Values that are valid but far from the training data still need monitoring, covered in a later chapter. - Validating inside the endpoint. Hand-written
ifchecks in the function duplicate the schema and drift from it. Keep rules in the model class so the generated documentation stays accurate.
Check your understanding
Exercise
A client sends {"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4} to /predict. What status code does the service return, and why does the model never run?
Show answer
It returns 422. The petal_width field is required and has no default, so Pydantic validation fails before the endpoint function is called. The response lists petal_width as missing.
Exercise
How would you change IrisFeatures so that petal_width must be greater than 0 and no larger than 10?
Show answer
Use petal_width: float = Field(gt=0, le=10).