Sub topic 8
Testing the API
This chapter assumes you have the main.py service from the earlier chapters and a model.joblib file in the same directory. You should also be comfortable with basic pytest usage. Install the test dependencies first:
pip install pytest httpxFastAPI's TestClient uses httpx, so it must be installed.
What to test
A model API has three things worth checking automatically:
- The happy path. A valid request returns status 200 and a response that matches the contract.
- Validation. A bad request is rejected before it reaches the model.
- Startup behavior. The model loads, and
/healthreports it.
You do not need to test scikit-learn itself. You are testing the service around the model.
Using TestClient
TestClient calls your app in-process. It sends requests without starting Uvicorn or opening a port, so tests run fast.
The common mistake is to create the client without a with block. FastAPI runs your lifespan code (the model loading) only when the client is used as a context manager. Without it, models["iris"] is never set, and /predict fails with a KeyError.
from fastapi.testclient import TestClient
from main import app
def test_predict_returns_class_index():
with TestClient(app) as client:
response = client.post(
"/predict",
json={
"sepal_length": 5.1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
},
)
assert response.status_code == 200
assert isinstance(response.json()["class_index"], int)
def test_predict_rejects_negative_values():
with TestClient(app) as client:
response = client.post(
"/predict",
json={
"sepal_length": -1,
"sepal_width": 3.5,
"petal_length": 1.4,
"petal_width": 0.2,
},
)
assert response.status_code == 422Save this as test_main.py and run pytest.
The first test checks the type of class_index rather than a specific value. That keeps the test stable if you retrain the model. The second test sends sepal_length: -1. The Field(gt=0) rule makes Pydantic reject it, and FastAPI answers with status 422 (Unprocessable Entity) before predict runs.
How a request flows in a test
Common errors
| Symptom | Likely cause |
|---|---|
| `KeyError: 'iris'` | The client was created without `with`, so the lifespan did not run. |
| `FileNotFoundError: model.joblib` | pytest was started from a different directory. The model path is relative to the working directory. |
| `RuntimeError` about `httpx` | `httpx` is not installed. |
| 422 where you expected 200 | The JSON field names do not match `IrisFeatures`. |
Other cases to cover
Add tests for missing fields, wrong types such as "abc" for a float, and the /health endpoint. For /health, assert that model_loaded is true inside a with block. That confirms the startup path works.
Exercise
Why does the test for /predict create the client with with TestClient(app) as client: instead of client = TestClient(app)?
Show answer
The with form runs the app's lifespan startup code, which loads the model into models. Without it, models["iris"] is never set and the request fails with a KeyError.
Exercise
Write a test that checks /health reports the model as loaded.
Show answer
Use the context manager, call the endpoint, and assert on the JSON. For example: with TestClient(app) as client: response = client.get("/health"), then assert response.status_code == 200 and assert response.json()["model_loaded"] is True.