Sub topic 3
Designing the request and response contract
This chapter assumes you can write basic Python classes, have trained a scikit-learn style model, and know what an HTTP request and JSON body are. Here you define what the API accepts and returns. The next chapter covers how that definition rejects bad input.
What the contract is
The contract is the agreement between your service and its callers. It states which fields a request must contain, what type each field has, and what shape the response takes. Callers write their code against this agreement, so changing it later can break them.
A model has no contract of its own. A scikit-learn model accepts a 2D array of numbers, and column order is the only thing that identifies a feature. If you expose that directly, a caller can send [[5.1, 3.5, 1.4, 0.2]] and have no way to tell which number is which. A named-field contract makes the meaning explicit.
Request schema
FastAPI uses Pydantic models to describe JSON bodies. Each class attribute is a field, and its annotation is the type.
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)This model does three things:
- It names each feature, so callers do not depend on column order.
- It fixes each type to
float. - It states a rule,
gt=0(greater than zero), that the next chapter uses for validation.
The service, not the caller, converts these named fields into the row the model expects. That keeps the model's internal ordering private, so you can change it without breaking anyone.
Response schema
Define the response as a model too:
class Prediction(BaseModel):
class_index: intWhen you pass it as response_model=Prediction on the endpoint, FastAPI checks and filters what you return. Extra keys are dropped, and the documented shape stays accurate. It also appears in the generated OpenAPI documentation at /docs.
Return a plain Python int, not a NumPy integer. model.predict returns NumPy types, and the JSON encoder may not accept them. Convert with int(...) before building the response.
How the pieces connect
Design choices
- Use named fields, not a bare list. A list of numbers is short, but a caller who swaps two values gets a wrong prediction with no error.
- Return a JSON object, not a bare value.
{"class_index": 0}can later gain fields such as a probability or a model version. A bare0cannot grow without breaking callers. - Keep names stable. Renaming
petal_lengthis a breaking change. Adding an optional field is not.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| Feature order in the service differs from training | Silent wrong predictions | Build the row in one place, in the training order |
| Returning NumPy values | Serialization error | Convert with `int()` or `float()` |
| No response model | Output shape drifts over time | Set `response_model` |
| Using `int` for a measurement | Decimals such as 5.1 are rejected or truncated, depending on settings | Use `float` |
Exercise
A teammate wants the endpoint to accept {"features": [5.1, 3.5, 1.4, 0.2]} because it is shorter. Give two reasons to prefer the named-field schema, and one reason you might still accept the list form.
Show answer
Named fields make each value's meaning explicit, and they let callers avoid silent mistakes from swapped values. They also keep the model's column order private, so the service can change it without breaking callers. The list form might be acceptable for a service with dozens or hundreds of features, where naming every field is impractical, as long as you validate the list length and document the order.