Sub topic 4
Validating input before it reaches the model
This chapter assumes you have the IrisFeatures model from the previous chapter and can run a FastAPI app with Uvicorn. You should know basic Python type hints. No Pydantic experience beyond the earlier example is needed.
Why validation sits in front of the model
A scikit-learn model accepts almost anything numeric. Pass it a negative petal length, a huge number, or NaN, and predict can still return a class index. A confident wrong answer is worse than an error, because the caller never learns anything went wrong.
Validation is the gate that stops bad input before the model sees it. It also gives callers a clear message about what to fix. FastAPI delegates this to Pydantic. Your request model declares the rules, and FastAPI applies them before your endpoint function runs.
What the basic model already does
The model from earlier chapters looks like this:
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)This already rejects several kinds of bad input:
- A missing field returns 422 with a "Field required" error.
- A non-numeric string such as
"abc"fails type conversion. - A zero or negative value fails the
gt=0constraint.
It leaves gaps, though. Four are worth closing.
Gaps in the basic model
Values that are valid but absurd
gt=0 accepts 1e12. Iris measurements are in centimeters and stay under about 10. A value of 5000 almost certainly means a unit error, such as millimeters sent instead of centimeters. Add an upper bound with le.
Infinity and NaN
Python's JSON parser accepts the non-standard tokens NaN and Infinity. Infinity passes gt=0. Setting allow_inf_nan=False rejects both explicitly, so the intent is visible in the schema.
Unknown fields
By default Pydantic ignores extra keys. If a client misspells petal_width as petal_widht, the request fails on the missing field, which is helpful. But if the client sends an extra, optional-looking field such as sepal_length_cm, the service silently drops it. Forbidding extras turns that into an error.
Strings that look like numbers
In the default lax mode, Pydantic converts the string "5.1" to the float 5.1. That is convenient, but it lets a sloppy client keep sending strings forever. Strict mode rejects it. Choose based on how much you control your clients.
A hardened request model
Here is the stricter version. It replaces IrisFeatures in main.py.
from pydantic import BaseModel, ConfigDict, Field
class IrisFeatures(BaseModel):
model_config = ConfigDict(extra="forbid", strict=True)
sepal_length: float = Field(gt=0, le=20, allow_inf_nan=False)
sepal_width: float = Field(gt=0, le=20, allow_inf_nan=False)
petal_length: float = Field(gt=0, le=20, allow_inf_nan=False)
petal_width: float = Field(gt=0, le=20, allow_inf_nan=False)What each setting does:
| Setting | Effect |
|---|---|
| `extra="forbid"` | Unknown keys produce a 422 error. |
| `strict=True` | No type coercion. `"5.1"` is rejected, but integers like `5` are still accepted for float fields. |
| `gt=0, le=20` | Values must be in the range (0, 20]. |
| `allow_inf_nan=False` | `NaN` and infinity are rejected. |
The upper bound of 20 is a judgment call. Pick a limit that is generous compared with your training data but still catches unit mistakes. Document it in the contract so callers know it.
What a rejection looks like
When validation fails, FastAPI returns status 422 (Unprocessable Content) and a JSON body listing every problem, not only the first. A request with a negative sepal_length and an extra field gets a response shaped like this:
{
"detail": [
{
"type": "greater_than",
"loc": ["body", "sepal_length"],
"msg": "Input should be greater than 0",
"input": -1,
"ctx": {"gt": 0}
},
{
"type": "extra_forbidden",
"loc": ["body", "color"],
"msg": "Extra inputs are not permitted",
"input": "red"
}
]
}The loc list tells the caller exactly which field failed. The exact wording of msg can change between Pydantic versions, so tests should check the status code and loc, not the message text.
Validating batches
The batch endpoint from the batching chapter takes a list of IrisFeatures. Each element is validated with the rules above, and the error loc includes the list index, for example ["body", "instances", 3, "sepal_length"]. That makes a bad row easy to find.
A list also needs a size limit. Without one, a single request can carry a million rows and tie up a worker for minutes. Use min_length and max_length:
class BatchRequest(BaseModel):
instances: list[IrisFeatures] = Field(min_length=1, max_length=1000)An empty list is rejected too. Calling predict on an empty array raises an error in scikit-learn, which would otherwise surface as a 500.
Checks that depend on more than one field
Some rules involve several fields at once. Pydantic handles these with a model_validator. This example is purely illustrative, so adapt the rule to your own data:
from pydantic import BaseModel, Field, model_validator
class Box(BaseModel):
width: float = Field(gt=0)
height: float = Field(gt=0)
@model_validator(mode="after")
def check_aspect_ratio(self):
ratio = self.width / self.height
if not 0.1 <= ratio <= 10:
raise ValueError("width/height ratio must be between 0.1 and 10")
return selfA ValueError raised in a validator becomes a 422 entry like any other failure. Keep these checks cheap and deterministic. They run on every request.
What validation cannot do
Validation checks that input is well formed and plausible. It does not check that the input resembles your training data. A request with petal_length=19 passes the bounds above, yet the model has never seen anything like it. Its prediction will be arbitrary.
Detecting inputs that are valid but unlike the training data is a monitoring task, covered in the logging and monitoring chapter. For now, treat validation as the first line of defense and not a guarantee of prediction quality.
Common mistakes
- Validating inside the endpoint. Writing
if x < 0: raise HTTPException(...)in the function body duplicates what the schema can express and hides the rules from the generated OpenAPI docs. Put the rules in the model. - Catching
ValidationErrorand returning 200. A client must be able to tell a failure from a result. Let the 422 through. - Using 400 for schema errors. FastAPI uses 422 by default. Pick one convention and keep clients consistent with it.
- Testing only the happy path. Every constraint you add should have a test that sends a violating value and checks for 422.
Testing the new rules
These tests extend the file from the testing chapter. They use the context-manager form of TestClient so the startup code loads the model.
from fastapi.testclient import TestClient
from main import app
VALID = {
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
}
def post_with(**overrides):
with TestClient(app) as client:
return client.post("/predict", json={**VALID, **overrides})
def test_rejects_value_above_upper_bound():
assert post_with(sepal_length=5000).status_code == 422
def test_rejects_numeric_string_in_strict_mode():
assert post_with(sepal_length="5.1").status_code == 422
def test_rejects_unknown_field():
assert post_with(color="red").status_code == 422
def test_error_points_at_the_bad_field():
response = post_with(petal_width=-1)
assert response.status_code == 422
assert response.json()["detail"][0]["loc"] == ["body", "petal_width"]Run them with pytest. If test_rejects_numeric_string_in_strict_mode fails, check that strict=True is set on the model.
Exercise
A client sends {"sepallength": 5.1, "sepalwidth": 3.5, "petallength": 1.4, "petalwidth": 0.2, "species": "setosa"} to the hardened /predict endpoint. What status code does it get, and what would it get with the original model that had no extra="forbid"?
Show answer
With extra="forbid" the request fails with 422, and the error has type "extra_forbidden" and loc ["body", "species"]. With the original model, Pydantic ignores unknown keys by default, so the request succeeds with 200 and the species value is silently dropped.
Exercise
Why is validation not enough to protect users from bad predictions? Name one kind of input that passes every rule in the hardened model yet is likely to produce a meaningless prediction.
Show answer
Validation only checks that values are well formed and inside the bounds you chose. It cannot tell whether an input resembles the training data. For example, petal_length=19 with the other values typical of setosa is within (0, 20], yet the model never saw such a flower, so its output is arbitrary. Detecting this needs monitoring of input distributions.