Sub topic 6
Building the prediction endpoint
This chapter assembles the pieces from the earlier chapters into a working POST /predict endpoint. It traces one request from the network to the model and back, and it covers the details that commonly go wrong.
It assumes you can read basic Python and FastAPI route functions, that you know how a scikit-learn model's predict works, and that you can read JSON and HTTP status codes. It also assumes model.joblib already exists from the training script in the saving chapter.
What the endpoint has to do
A prediction endpoint is a thin adapter between HTTP and the model. On each request it does four things:
- Parse the JSON body and validate it against the request schema.
- Turn the validated fields into the numeric layout the model expects.
- Call the model that was loaded at startup.
- Convert the result into the response schema.
The endpoint should contain no training logic, no file loading, and no business rules beyond this mapping. Keeping it thin makes it easy to test and easy to replace later.
The complete service
This is the full main.py. The schemas and the startup hook come from earlier chapters. The new part is the /predict function at the bottom.
from contextlib import asynccontextmanager
import joblib
from fastapi import FastAPI
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)
class Prediction(BaseModel):
class_index: int
models = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
models["iris"] = joblib.load("model.joblib")
yield
models.clear()
app = FastAPI(lifespan=lifespan)
@app.get("/health")
def health():
return {"status": "ok", "model_loaded": "iris" in models}
@app.post("/predict", response_model=Prediction)
def predict(features: IrisFeatures):
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
prediction = models["iris"].predict(row)[0]
return Prediction(class_index=int(prediction))Reading the endpoint line by line
The signature does the validation
def predict(features: IrisFeatures) tells FastAPI to read the request body as JSON and build an IrisFeatures object from it. If a field is missing, has the wrong type, or fails gt=0, FastAPI answers with status 422 and never calls your function. Inside the function, you can rely on four positive floats.
Feature order is part of the contract
The model was trained on plain arrays, so it has no idea what the columns are called. It reads them by position. The row must be in the same order as the training data: sepal length, sepal width, petal length, petal width.
If you swap two values, nothing fails. You just get wrong predictions. Build the row in one place, as above, and treat the order as something to test.
The model expects a 2D input
predict takes shape (n_samples, n_features). A single request is one sample, so the row is a list that contains one list. That is why there are double brackets. The model returns an array with one entry per sample, and [0] takes the entry for your single row.
Convert NumPy types explicitly
The array holds NumPy integers, not Python integers. int(prediction) converts the value before it goes into the response. This keeps the response independent of how a given library version handles NumPy types.
`response_model` guards the output
response_model=Prediction makes FastAPI check and serialize the return value against the response schema. It also puts that schema in the generated OpenAPI documentation at /docs. If the function returns something with the wrong shape, the failure shows up on the server instead of in a client's parser.
Why the function is `def`, not `async def`
model.predict is CPU-bound, blocking work. FastAPI runs a plain def route in a thread pool, so one slow prediction does not freeze the event loop that handles other requests. If you wrote async def and called predict inside it, the call would block the event loop for its full duration. The concurrency chapter returns to this.
Running it and calling it
uvicorn main:app --port 8000
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{"sepal_length": 5.1, "sepal_width": 3.5, "petal_length": 1.4, "petal_width": 0.2}'Run the uvicorn command in one terminal and curl in another. The server prints startup messages, and the request returns this body:
{"class_index":0}Class 0 is setosa in the iris dataset. The service returns the index only. Whether to return a label as well is a decision about the API contract, and changing it later affects every client.
Now send a bad request, with "sepal_length": -1. The response has status 422, and the body is similar to this:
{"detail":[{"type":"greater_than","loc":["body","sepal_length"],"msg":"Input should be greater than 0","input":-1,"ctx":{"gt":0}}]}The loc field points at the offending field, so clients can show a precise message.
Status codes you should expect
| Status | Meaning here | Who caused it |
|---|---|---|
| 200 | Valid input, prediction returned | Nobody, normal path |
| 422 | Body failed schema validation | The client |
| 500 | Unhandled exception, such as a missing model | The service |
| 503 | Service is up but cannot predict yet | The service, temporarily |
The line models["iris"] raises KeyError if the model is not in the dictionary. Normally the startup hook guarantees it is there, because the app does not accept requests until lifespan has run. Still, a defensive check gives callers a clearer signal than a generic 500. Here is an optional variant of the endpoint that returns 503:
from fastapi import HTTPException
@app.post("/predict", response_model=Prediction)
def predict(features: IrisFeatures):
model = models.get("iris")
if model is None:
raise HTTPException(status_code=503, detail="Model not loaded")
row = [[
features.sepal_length,
features.sepal_width,
features.petal_length,
features.petal_width,
]]
prediction = model.predict(row)[0]
return Prediction(class_index=int(prediction))Use this version in place of the original predict, and add the HTTPException import at the top of main.py. Do not define both functions with the same route.
Common errors
- Wrong feature order. The model returns plausible but wrong classes. Keep the row construction in a single function and cover it with a test that uses a known input.
- Passing a flat list.
predict([5.1, 3.5, 1.4, 0.2])raises a scikit-learn error about expecting a 2D array. Wrap the row in an outer list. - Returning a NumPy value. A bare
predictionmay fail to serialize or may serialize differently across versions. Convert withint()orfloat(). - Loading the model at import time.
modelsis filled only when the app starts, so code that readsmodels["iris"]at import time fails. Access it inside request handlers. - Using
async defwith blocking code. Latency of unrelated requests rises under load, because they all wait on the one blocked event loop. - Mismatched library versions. A model saved with one scikit-learn version can warn or break when loaded under another. Pin versions in
requirements.txt.
What this endpoint does not do yet
Several concerns are deliberately left for later chapters:
- Automated tests, including the lifespan-aware
TestClient. - A batch route that scores many rows in one model call.
- Logging of inputs, outputs, and latency.
- Authentication and rate limits.
- A model version in the response.
Each one attaches to this endpoint without changing its basic shape.
Exercise
A teammate changes the endpoint to build the row as [[features.petallength, features.petalwidth, features.sepallength, features.sepalwidth]]. The service still starts, and every request returns 200. What happens, and how would you catch it?
Show answer
The model reads columns by position, so it now treats petal values as sepal values and the reverse. It returns 200 with wrong, but plausible, class indices, and nothing raises an error. Catch it with a test that sends a known input, such as 5.1, 3.5, 1.4, 0.2, and asserts the expected class (0). Also keep the row construction in one place so the order is defined once.
Exercise
Why does a request with "petal_width": 0 return 422 without the predict function running, and what status would you return if the model dictionary were empty?
Show answer
Field(gt=0) requires values strictly greater than zero. FastAPI validates the body against IrisFeatures before it calls the function, so zero fails validation and the client gets 422. If the model dictionary were empty, the failure is on the server side, so return 503 (service unavailable) by raising HTTPException(status_code=503), not 422 and not an unhandled 500.