Sub topic 6
Building the prediction endpoint
This chapter assumes you can write basic Python, have trained a scikit-learn model, and know how HTTP and JSON work. It also assumes you have the earlier pieces in place. Those are a saved model.joblib, the typed request model, and the startup loading pattern. Here you put them together into one working endpoint.
What the endpoint does
A prediction endpoint is a URL that accepts features and returns the model's output. It does four jobs in order:
- Receive a JSON body and check it against the request schema.
- Turn the validated fields into the row format the model expects.
- Call the model that was loaded at startup.
- Convert the result into plain Python types and return it in the response schema.
The complete service
Save this as main.py. It assumes model.joblib sits in the same directory.
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))How the handler works
The parameter features: IrisFeatures tells FastAPI to parse the request body as JSON and validate it. If validation fails, FastAPI returns status 422 and your function never runs. Inside the handler you can trust that all four values are positive floats.
scikit-learn's predict expects a 2D structure with one inner list per sample. That is why row is a list containing one list. Passing a flat list raises an error about expected 2D input.
predict returns a NumPy array, and [0] takes the first element. That element is a numpy.int64, which is not a plain Python int. Wrapping it in int() avoids serialization problems.
The response_model=Prediction argument makes the output shape part of the contract. FastAPI filters and validates what you return, and it documents the shape in the generated OpenAPI page at /docs.
The handler is declared with def, not async def. FastAPI runs plain functions in a worker thread pool, so a slow predict call does not freeze the event loop. Chapter on concurrency covers this in more detail.
Running 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}'The response for this input is {"class_index":0}, which is the setosa class in the iris dataset.
Common errors
| Symptom | Likely cause |
|---|---|
| `KeyError: 'iris'` | The model was not loaded. Check that the lifespan function ran, for example when a test creates `TestClient` without a `with` block. |
| `FileNotFoundError` at startup | `model.joblib` is not in the working directory where Uvicorn started. |
| Error about expected 2D array | You passed a flat list to `predict` instead of a list of rows. |
| Error encoding `numpy.int64` | The prediction was returned without `int()`. |
| 422 response | The body failed validation, for example a missing field or a value of 0 or less. |
Exercise
A teammate changes the handler to prediction = models["iris"].predict(row) and returns {"class_index": prediction[0]} without int(). What is likely to go wrong, and where should the fix go?
Show answer
prediction[0] is a numpy.int64, which may fail to serialize or fail validation. Wrap it with int(...) in the handler, as in Prediction(class_index=int(prediction[0])), so the response contains a plain Python integer.