Sub topic 3
Designing the request and response contract
This chapter assumes you can read Python type hints and know what a JSON body and an HTTP status code are. It also assumes you have trained a scikit-learn model, as in the earlier chapters. Here you design the interface between callers and the model. The next chapter covers how the service enforces that interface.
What a contract is
A contract is the written agreement about what a caller sends and what the service returns. It covers:
- the URL path and HTTP method
- the names and types of the request fields
- the shape of a successful response
- the shape and status codes of errors
The model does not know about any of this. A scikit-learn model takes a 2D array and returns an array. The contract translates between that array interface and something a client written in another language can use.
You design the contract before writing the endpoint. Callers build against it, so changing it later costs more than changing the code behind it.
Describing the contract as types
FastAPI uses Pydantic classes to declare the contract. The same declaration is used to parse requests, check types, shape responses, and generate documentation.
from pydantic import BaseModel, Field
class IrisFeatures(BaseModel):
sepal_length: float = Field(gt=0, description="Sepal length in cm")
sepal_width: float = Field(gt=0, description="Sepal width in cm")
petal_length: float = Field(gt=0, description="Petal length in cm")
petal_width: float = Field(gt=0, description="Petal width in cm")
class Prediction(BaseModel):
class_index: intIrisFeatures is the request and Prediction is the response. A valid request body looks like this:
{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}A valid response body looks like this:
{"class_index": 0}The Field(gt=0) constraints are part of the contract, because they state what values are acceptable. How they are enforced, and what the caller sees when they fail, is the subject of the next chapter.
Decisions that shape the contract
Named fields or a positional array
You could accept {"features": [5.1, 3.5, 1.4, 0.2]}. This is short and maps directly to the model's input. It is also fragile. The caller must know the column order, and swapping two values still passes type checks and silently gives a wrong prediction.
Named fields cost a few more bytes. They document themselves, they let the service reject a missing field by name, and they let you reorder the model's columns internally without telling anyone. For tabular models with a handful of features, prefer named fields.
For models with hundreds of features, such as embeddings, a list is often the practical choice. In that case validate its length and document the order explicitly.
Names and units
Use the names callers would expect, not the names from your training notebook. The scikit-learn iris dataset calls a column sepal length (cm), which is not a usable JSON key. Use snake_case names without spaces or punctuation. Put units in the field description, or in the name if two units are plausible, such as distance_km.
Keep the mapping from contract names to model columns in one place, the code that builds the row. The row order must match the order used in training.
def to_row(features: IrisFeatures) -> list[float]:
return [
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]What the response should contain
The model returns 0, 1, or 2. The minimal response returns that number as class_index. The name class_index tells the caller it is an index, not a label.
Callers usually want more than the raw output. Common additions are a human-readable label, class probabilities from predict_proba, and the model version. Each addition is a promise you must keep, so add only what a caller has asked for. Adding a field later is a safe change, while removing or renaming one breaks callers.
Return a JSON object rather than a bare value such as 0. An object can gain fields without breaking anyone. A bare number cannot.
Extra and missing fields
Pydantic ignores unknown fields by default. A request with a misspelled optional field is accepted, and the typo is silently dropped. You can make the contract stricter:
from pydantic import BaseModel, ConfigDict, Field
class StrictIrisFeatures(BaseModel):
model_config = ConfigDict(extra="forbid")
sepal_length: float = Field(gt=0)
sepal_width: float = Field(gt=0)
petal_length: float = Field(gt=0)
petal_width: float = Field(gt=0)| Policy | Behavior | Trade-off |
|---|---|---|
| Ignore extra fields (default) | Unknown keys are dropped | Tolerant of newer clients, but hides typos |
| `extra="forbid"` | Unknown keys cause a 422 error | Catches typos, but breaks clients that send additional data |
Avoid optional fields with silent defaults for model inputs. If petal_width defaults to 0.0 when omitted, the model scores a value the caller never sent. Make features required unless the model was trained to handle missing values.
Errors are part of the contract
Callers write code for failure cases too. Decide which status codes the service uses and keep them consistent.
| Status | Meaning in this service | Who must act |
|---|---|---|
| 200 | Prediction returned | Nobody |
| 422 | The body is malformed or violates the schema | Caller fixes the request |
| 500 | Unexpected failure in the service or model | Service owner |
| 503 | Service not ready, for example the model has not loaded | Caller retries later |
FastAPI returns 422 for schema violations. The body contains a detail list that names the failing location and reason. In abbreviated form, a request missing petal_width produces:
{
"detail": [
{"type": "missing", "loc": ["body", "petal_width"], "msg": "Field required"}
]
}The split between 4xx and 5xx matters. A 4xx status says the caller's request was wrong, so retrying the same request will not help. A 5xx status says the fault is on the service side, so a retry may succeed. Clients and load balancers use this distinction to decide whether to retry.
Letting the framework publish the contract
FastAPI builds an OpenAPI document from your Pydantic classes and serves it at /openapi.json. It also serves an interactive page at /docs. You can inspect the schema without starting a server:
import json
from pydantic import BaseModel, Field
class IrisFeatures(BaseModel):
sepal_length: float = Field(gt=0, description="Sepal length in cm")
sepal_width: float = Field(gt=0, description="Sepal width in cm")
petal_length: float = Field(gt=0, description="Petal length in cm")
petal_width: float = Field(gt=0, description="Petal width in cm")
print(json.dumps(IrisFeatures.model_json_schema(), indent=2))The output lists each property with its type, its exclusiveMinimum constraint, and its description. It also lists all four names under required. Client teams can generate typed client code from this document, so the code is the single source of truth and the documentation cannot drift from it.
When you connect the response class to an endpoint, use response_model=Prediction on the route, as in the chapter on the prediction endpoint. That filters the output to the declared fields and documents the response shape in OpenAPI.
Common mistakes
- Exposing training column names. Keys like
sepal length (cm)force awkward client code. Choose clean names and map them internally. - Returning a bare value or a bare array. You cannot add fields later without breaking callers.
- Returning NumPy types.
numpy.int64is not JSON-serializable by the standard encoder. Convert withint(...)before building the response, as thePredictionexamples in this tutorial do. - Defaulting missing features. The model scores data the caller never supplied, and nothing signals the problem.
- Changing meaning without changing shape. If
class_indexstarts meaning something different after retraining, the JSON is unchanged but callers break. The chapter on versioning covers this. - Letting the contract mirror the model object. Do not design the API around whatever
predicthappens to accept. Design it around what callers need, and write the translation code.
Summary
The contract is a small set of Pydantic classes plus a status code policy. Use named, clean field names and return a JSON object. Decide how to treat extra and missing fields on purpose, and convert NumPy values to plain Python types. FastAPI turns these classes into live documentation, which keeps the written contract and the running service in agreement.
Exercise
Your iris service currently returns {"class_index": 0}. A client team asks for the flower's name ("setosa") and the model's confidence. Without breaking existing clients, how would you change the response contract, and which change would break them?
Show answer
Add new fields to the response object, for example {"classindex": 0, "classname": "setosa", "probability": 0.98}. Existing clients read only classindex and ignore the new keys, so adding fields is safe. Changing classindex to a string, renaming it to "label", removing it, or returning the name as a bare string instead of an object would break existing clients. Convert any NumPy values, such as the probability from predict_proba, to plain Python floats before building the response.
Exercise
A request is sent with the key "petal_lenght" (a typo) and the other three fields correct. With the default Pydantic settings, what happens, and what change to the model class makes the service report the typo?
Show answer
Because petallength is required, the request is rejected with a 422 error that says the field is missing. If the field had been optional with a default, the typo would be silently ignored and the default used. Setting modelconfig = ConfigDict(extra="forbid") on the request class makes any unknown key such as "petal_lenght" an error in itself.