Skip to main content

AI and machine learning · Intermediate · 24 min

Serve a scikit-learn model as an API with FastAPI

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · FastAPI 0.165.0 · uvicorn 0.54.0 · scikit-learn 1.9.1 · skops 0.16.0

You will have a FastAPI service that loads a saved scikit-learn pipeline once at startup, rejects bad input, returns a churn probability with the model version for one customer or a capped batch, logs every prediction for drift checks without personal data, and passes a TestClient test suite.

On this page

A trained model in a file helps nobody until other software can ask it questions. The usual answer is a small HTTP service: a mobile app, a CRM or a nightly job sends customer details as JSON and gets a prediction back. The service has more to do than call predict_proba. It has to load the model once rather than on every request, refuse input the model was never trained on, say which model answered, cap how much work one request can ask for, and keep a record that lets you notice when the world changes under the model.

In this tutorial you build that service with FastAPI and uvicorn for the churn model from build a scikit-learn pipeline with ColumnTransformer. The first step trains and saves a copy of that pipeline, so you do not need to have kept anything from it. Everything runs on a laptop CPU, the data is generated with a fixed seed, and no real person is in it.

Step 1 · Create the project and install pinned versions

Make a throwaway folder and a virtual environment, and install exact versions. The service that loads a model must run the same scikit-learn version that saved it, so pinning here is part of correctness, not tidiness:

Bash
mkdir -p ~/churn-api-demo
cd ~/churn-api-demo
python3 -m venv .venv
source .venv/bin/activate
pip install --quiet fastapi==0.165.0 starlette==1.10.0 uvicorn==0.54.0 pydantic==2.14.4 \
  scikit-learn==1.9.1 pandas==3.1.1 numpy==2.5.5 skops==0.16.0

The download is around 90 MB, mostly NumPy, SciPy and pandas. On prepaid mobile data, run it once on Wi-Fi; nothing later needs a connection.

Check it worked

Bash
python -c "import fastapi, uvicorn, sklearn, skops; print(fastapi.__version__, uvicorn.__version__, sklearn.__version__, skops.__version__)"

The output is 0.165.0 0.54.0 1.9.1 0.16.0.

Step 2 · Train and save the model

This script generates 3,000 customers, fits the same imputing, scaling and one-hot pipeline as the ColumnTransformer tutorial, and saves it with skops. The earlier tutorial explains each part; here it is condensed into one file:

Bash
cat > train.py <<'PY'
import numpy as np
import pandas as pd
import skops.io as sio
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

rng = np.random.default_rng(42)
n = 3000
plans = rng.choice(["prepaid", "postpaid", "business"], size=n, p=[0.6, 0.3, 0.1])
cities = rng.choice(["Lagos", "Nairobi", "Accra", "Johannesburg"], size=n)
tenure = rng.integers(1, 61, size=n)
spend = rng.gamma(shape=2.0, scale=15.0, size=n).round(2)
calls = rng.poisson(1.5, size=n)
score = (-1.0 - 0.04 * tenure + 0.6 * calls + 1.2 * (plans == "prepaid")
         - 0.02 * spend + 0.5 * (cities == "Lagos"))
churned = (rng.random(n) < 1 / (1 + np.exp(-score))).astype(int)

X = pd.DataFrame({"tenure_months": tenure, "monthly_spend": spend,
                  "support_calls": calls, "plan": plans, "city": cities})
X.loc[rng.random(n) < 0.08, "monthly_spend"] = np.nan
X.loc[rng.random(n) < 0.05, "plan"] = None

preprocess = ColumnTransformer([
    ("num", Pipeline([("impute", SimpleImputer(strategy="median")),
                      ("scale", StandardScaler())]),
     ["tenure_months", "monthly_spend", "support_calls"]),
    ("cat", Pipeline([("impute", SimpleImputer(strategy="most_frequent")),
                      ("onehot", OneHotEncoder(handle_unknown="ignore", sparse_output=False))]),
     ["plan", "city"]),
])
model = Pipeline([("prep", preprocess), ("clf", LogisticRegression(max_iter=1000))])
model.fit(X, churned)

sio.dump(model, "churn-model.skops")
print("saved churn-model.skops, trained on", len(X), "rows")
PY
python train.py

In your own work this file comes from a training job, and the service only ever reads it. skops is used instead of pickle or joblib because a pickle file can run code while it loads; skops lists the types inside the file so you can refuse anything you have not reviewed.

Check it worked

The script prints saved churn-model.skops, trained on 3000 rows, and ls -l churn-model.skops shows a file of roughly 180 KB.

Step 3 · Write the service

Create app.py. Read it top to bottom once; the sections after the code explain the three parts that matter.

Bash
cat > app.py <<'PY'
import hashlib
import json
import logging
import os
import uuid
from contextlib import asynccontextmanager
from datetime import datetime, timezone
from typing import Literal

import pandas as pd
import skops.io as sio
import sklearn
from fastapi import FastAPI, Request
from pydantic import BaseModel, ConfigDict, Field

MODEL_PATH = os.environ.get("MODEL_PATH", "churn-model.skops")
REVIEWED_TYPES = {"numpy.dtype"}
# Column order and dtypes the pipeline was trained with.
DTYPES = {
    "tenure_months": "int64",
    "monthly_spend": "float64",
    "support_calls": "int64",
    "plan": "str",
    "city": "str",
}
THRESHOLD = 0.5

prediction_log = logging.getLogger("predictions")
prediction_log.setLevel(logging.INFO)
prediction_log.propagate = False


@asynccontextmanager
async def lifespan(app: FastAPI):
    unknown = set(sio.get_untrusted_types(file=MODEL_PATH))
    if unknown - REVIEWED_TYPES:
        raise RuntimeError(f"unreviewed types in {MODEL_PATH}: {sorted(unknown - REVIEWED_TYPES)}")
    app.state.model = sio.load(MODEL_PATH, trusted=sorted(REVIEWED_TYPES))
    with open(MODEL_PATH, "rb") as f:
        app.state.model_version = "churn-" + hashlib.sha256(f.read()).hexdigest()[:12]

    handler = logging.FileHandler(os.environ.get("PREDICTION_LOG", "predictions.log"))
    handler.setFormatter(logging.Formatter("%(message)s"))
    prediction_log.addHandler(handler)
    yield
    prediction_log.removeHandler(handler)
    handler.close()


app = FastAPI(title="Churn model API", version="1.0.0", lifespan=lifespan)


class Customer(BaseModel):
    model_config = ConfigDict(extra="forbid")

    tenure_months: int = Field(ge=0, le=600)
    monthly_spend: float | None = Field(default=None, ge=0, le=10_000)
    support_calls: int = Field(ge=0, le=100)
    plan: Literal["prepaid", "postpaid", "business"] | None = None
    city: str = Field(min_length=1, max_length=60)


class Prediction(BaseModel):
    model_version: str
    churn_probability: float
    likely_to_churn: bool


def score(request: Request, customers: list[Customer], endpoint: str) -> list[Prediction]:
    rows = pd.DataFrame([c.model_dump() for c in customers], columns=list(DTYPES))
    rows = rows.astype(DTYPES)
    probabilities = request.app.state.model.predict_proba(rows)[:, 1]
    version = request.app.state.model_version

    request_id = str(uuid.uuid4())
    now = datetime.now(timezone.utc).isoformat(timespec="seconds")
    results = []
    for customer, p in zip(customers, probabilities):
        p = round(float(p), 3)
        prediction_log.info(json.dumps({
            "ts": now,
            "request_id": request_id,
            "endpoint": endpoint,
            "model_version": version,
            "input": customer.model_dump(),
            "churn_probability": p,
        }))
        results.append(Prediction(model_version=version, churn_probability=p,
                                  likely_to_churn=p >= THRESHOLD))
    return results


@app.get("/healthz")
def healthz(request: Request):
    return {"status": "ok", "model_version": request.app.state.model_version,
            "scikit_learn": sklearn.__version__}


@app.post("/predict", response_model=Prediction)
def predict(customer: Customer, request: Request):
    return score(request, [customer], "predict")[0]
PY

Load once, at startup

lifespan runs once when the server starts, before the first request, and the code after yield runs once when it stops. Loading the model there means every request reuses the same object in app.state, instead of reading 180 KB from disk and rebuilding the pipeline each time. If the file is missing, or holds a type outside REVIEWED_TYPES, the exception stops the server from starting at all. That is the behaviour you want: a load balancer or /healthz check sees a dead service, rather than one that answers every request with an error.

The model version is the first 12 characters of the file's SHA-256 hash. It changes whenever the file changes, so a prediction can always be traced to the exact file that made it, without anyone remembering to bump a number.

Validate before the model sees anything

Customer describes what the model accepts. FastAPI checks every request body against it and answers 422 Unprocessable Content with the reason when it fails, so score never runs on bad data:

  • Ranges (ge, le) stop negative tenure or a support-call count of 10,000, which the model would happily turn into a confident nonsense probability.
  • plan is a Literal: three values the model knows, or nothing. A city is free text because the encoder already handles unseen cities, but it cannot be empty or longer than 60 characters.
  • extra="forbid" rejects any field the model does not use. A client that sends a name, phone number or email gets a 422, so personal data never gets as far as the log.

Rebuild the training dtypes

rows.astype(DTYPES) looks like housekeeping, but it fixes a real bug. When a client leaves plan out, Pydantic gives None. In a plain pandas column, None stays None, and SimpleImputer only treats NaN as missing, so the missing plan is passed through as a category called None, the encoder ignores it, and the customer is scored as if they had no plan. Casting to the str dtype turns None into NaN, because pandas 3 (pinned here at 3.1.1) uses NaN as the missing value of its str dtype; on pandas 2, astype('str') gives the literal string 'None' and the bug comes back silently. With the cast, the imputer fills in the most common plan, and the prediction matches what the pipeline did in training. One of the tests later catches this if anyone removes the cast.

Check it worked

Bash
python -c "import app; print(app.app.title, app.THRESHOLD)"

The output is Churn model API 0.5. Importing the module does not load the model; only starting the server does.

Step 4 · Start the server and call it with curl

In your second terminal, start uvicorn from the project folder and leave it running:

Bash
cd ~/churn-api-demo
source .venv/bin/activate
uvicorn app:app --host 127.0.0.1 --port 8000

uvicorn prints Application startup complete. once lifespan has loaded the model, then Uvicorn running on http://127.0.0.1:8000. 127.0.0.1 means only your own machine can reach it.

Back in the first terminal, ask for the health check, then score three customers: a new prepaid customer in Lagos with four support calls, a long-standing postpaid customer in Nairobi with no spend figure, and a customer in Kumasi, a city the model never saw, with no plan:

Bash
curl -s -w '\n' http://127.0.0.1:8000/healthz
curl -s -w '\n' --json '{"tenure_months": 3, "monthly_spend": 12.5, "support_calls": 4, "plan": "prepaid", "city": "Lagos"}' http://127.0.0.1:8000/predict
curl -s -w '\n' --json '{"tenure_months": 48, "support_calls": 0, "plan": "postpaid", "city": "Nairobi"}' http://127.0.0.1:8000/predict
curl -s -w '\n' --json '{"tenure_months": 12, "monthly_spend": 40, "support_calls": 1, "city": "Kumasi"}' http://127.0.0.1:8000/predict

--json sends the body with a JSON content type. -w '\n' adds a newline, because FastAPI's responses end without one.

Now send something the service must refuse: negative tenure, an unknown plan and an email address:

Bash
curl -s -w '\n%{http_code}\n' --json '{"tenure_months": -2, "support_calls": 1, "plan": "gold", "city": "Accra", "email": "someone@example.com"}' http://127.0.0.1:8000/predict

Check it worked

The health check shows your model version, something like {"status":"ok","model_version":"churn-38a1f18ba431","scikit_learn":"1.9.1"}. Your hash will differ, because the saved file records when it was written.

The three predictions carry the same version and probabilities of about 0.925 (Lagos, "likely_to_churn":true), 0.035 (Nairobi) and 0.392 (Kumasi). The last command prints a detail list with three errors, of types greater_than_equal, literal_error and extra_forbidden, and then 422.

Step 5 · Add a batch endpoint with a size limit

Scoring customers one request at a time is slow for a nightly job or for a field app that queued fifty visits while offline. That second case matters wherever sales agents work on low-end Android phones with patchy, prepaid data: one request when the signal returns is cheaper and more reliable than fifty. A batch endpoint helps, but without a limit one request can ask the server to score a million rows and starve everyone else. Append the endpoint to app.py:

Bash
cat >> app.py <<'PY'


MAX_BATCH = 100


class Batch(BaseModel):
    customers: list[Customer] = Field(min_length=1, max_length=MAX_BATCH)


@app.post("/predict/batch", response_model=list[Prediction])
def predict_batch(batch: Batch, request: Request):
    return score(request, batch.customers, "batch")
PY

Every customer in the list goes through the same Customer checks, and score sends them to the model as one DataFrame, which is much faster than a loop of single predictions. Results come back in the order they were sent. The list limit is checked after the JSON is parsed, so also cap the request body size at your reverse proxy in production.

uvicorn does not reload on its own here. In the second terminal, press Ctrl+C and start it again:

Bash
uvicorn app:app --host 127.0.0.1 --port 8000

Send two customers, then 101, then none:

Bash
cat > batch.json <<'JSON'
{"customers": [
  {"tenure_months": 3, "monthly_spend": 12.5, "support_calls": 4, "plan": "prepaid", "city": "Lagos"},
  {"tenure_months": 48, "support_calls": 0, "plan": "postpaid", "city": "Nairobi"}
]}
JSON
curl -s -w '\n' --json @batch.json http://127.0.0.1:8000/predict/batch
python3 -c "import json; print(json.dumps({'customers': [{'tenure_months': 5, 'support_calls': 1, 'city': 'Accra'}] * 101}))" > too-big.json
curl -s -o /dev/null -w '%{http_code}\n' --json @too-big.json http://127.0.0.1:8000/predict/batch
curl -s -w '\n' --json '{"customers": []}' http://127.0.0.1:8000/predict/batch

Check it worked

The first call returns a JSON list of two predictions, about 0.925 then 0.035, the same numbers as the single endpoint. The 101-customer request prints 422. The empty list returns a too_short error that says the list should have at least 1 item.

Step 6 · Read the prediction log for drift

Every successful prediction wrote one JSON line to predictions.log. Look at the last one:

Bash
tail -n 1 predictions.log

A line holds the time, a request ID shared by every row of one batch, the endpoint, the model version, the validated input and the probability. Nothing else: no IP address, no headers, no customer ID. Because extra="forbid" rejected anything outside the five model features, a name or phone number cannot reach this file even by mistake. Five coarse features can still single out a person in a small town, so treat the log as business data anyway: keep it only as long as the drift checks need it.

uvicorn's own access log, the lines in the second terminal, is separate and does record the client's address and path. If you do not need it, start uvicorn with --no-access-log.

The point of the log is to compare what the model sees now with what it was trained on. Write a short report:

Bash
cat > drift_report.py <<'PY'
import json
import sys

import skops.io as sio

model = sio.load("churn-model.skops", trusted=["numpy.dtype"])
onehot = model.named_steps["prep"].named_transformers_["cat"].named_steps["onehot"]
known_cities = set(onehot.categories_[1])

rows = [json.loads(line) for line in open(sys.argv[1] if len(sys.argv) > 1 else "predictions.log")]
n = len(rows)
inputs = [r["input"] for r in rows]

print("rows:", n)
print("model versions:", sorted({r["model_version"] for r in rows}))
print("mean churn probability:", round(sum(r["churn_probability"] for r in rows) / n, 3))
print("missing monthly_spend:", f"{sum(i['monthly_spend'] is None for i in inputs) / n:.0%}")
print("missing plan:", f"{sum(i['plan'] is None for i in inputs) / n:.0%}")
print("cities not seen in training:", f"{sum(i['city'] not in known_cities for i in inputs) / n:.0%}")
PY
python drift_report.py

The list of known cities comes from the fitted encoder itself, so it can never disagree with the model. In training, about 8% of spend values and 5% of plans were missing and every city was known. When these shares move a long way from that, or the mean probability creeps up week on week, the model is being asked about customers it did not learn from, and it is time to look at retraining.

Check it worked

The tail shows one line ending in "churn_probability": 0.035} from the batch call. The report says rows: 5, one model version, a mean churn probability of about 0.462, 40% missing spend, 20% missing plan and 20% unseen cities (Kumasi). If you ran a curl command twice, your counts are higher; the invalid requests are not in the log because they never reached the model.

Step 7 · Test the service with TestClient

curl proves it works today. Tests prove it still works after the next change. FastAPI's TestClient calls the app in-process, with no server or port. Starlette 1.10 (pinned at 1.10.0 in the first install) expects the httpx2 package for it and warns if it finds only the old httpx, so install that with pytest:

Bash
pip install --quiet pytest==9.2.0 httpx2==2.16.2

Create test_app.py. The fixture points the prediction log at a temporary folder, so tests never write into your real log, and uses TestClient in a with block, which is what makes lifespan run:

Bash
cat > test_app.py <<'PY'
import json

import pytest
from fastapi.testclient import TestClient

from app import app

LAGOS = {"tenure_months": 3, "monthly_spend": 12.5, "support_calls": 4,
         "plan": "prepaid", "city": "Lagos"}


@pytest.fixture
def client(tmp_path, monkeypatch):
    monkeypatch.setenv("PREDICTION_LOG", str(tmp_path / "predictions.log"))
    with TestClient(app) as c:
        yield c


def test_healthz_reports_model_version(client):
    body = client.get("/healthz").json()
    assert body["status"] == "ok"
    assert body["model_version"].startswith("churn-")


def test_predict_returns_probability_and_version(client):
    r = client.post("/predict", json=LAGOS)
    assert r.status_code == 200
    body = r.json()
    assert 0.8 < body["churn_probability"] <= 1
    assert body["likely_to_churn"] is True
    assert body["model_version"] == client.get("/healthz").json()["model_version"]


def test_missing_plan_is_imputed_not_ignored(client):
    without_plan = {k: v for k, v in LAGOS.items() if k != "plan"}
    p_missing = client.post("/predict", json=without_plan).json()["churn_probability"]
    p_prepaid = client.post("/predict", json=LAGOS).json()["churn_probability"]
    assert p_missing == p_prepaid  # prepaid is the most common plan in training


@pytest.mark.parametrize("field, value", [
    ("tenure_months", -1),
    ("support_calls", 1000),
    ("plan", "gold"),
    ("city", ""),
])
def test_rejects_out_of_range_input(client, field, value):
    r = client.post("/predict", json={**LAGOS, field: value})
    assert r.status_code == 422


def test_rejects_extra_fields_such_as_email(client):
    r = client.post("/predict", json={**LAGOS, "email": "someone@example.com"})
    assert r.status_code == 422
    assert r.json()["detail"][0]["type"] == "extra_forbidden"


def test_batch_keeps_order_and_enforces_limit(client):
    nairobi = {"tenure_months": 48, "support_calls": 0, "plan": "postpaid", "city": "Nairobi"}
    r = client.post("/predict/batch", json={"customers": [LAGOS, nairobi]})
    assert r.status_code == 200
    first, second = r.json()
    assert first["churn_probability"] > second["churn_probability"]
    assert client.post("/predict/batch", json={"customers": [LAGOS] * 101}).status_code == 422
    assert client.post("/predict/batch", json={"customers": []}).status_code == 422


def test_log_holds_model_inputs_only(client, tmp_path):
    client.post("/predict", json=LAGOS)
    line = json.loads((tmp_path / "predictions.log").read_text().splitlines()[-1])
    assert set(line) == {"ts", "request_id", "endpoint", "model_version", "input", "churn_probability"}
    assert set(line["input"]) == set(LAGOS)


def test_startup_fails_when_model_is_missing(monkeypatch):
    monkeypatch.setattr("app.MODEL_PATH", "no-such-model.skops")
    with pytest.raises(FileNotFoundError):
        with TestClient(app):
            pass
PY
python -m pytest -q

test_missing_plan_is_imputed_not_ignored guards the dtype fix from the service step: delete the astype line and it fails. The last test proves that a missing model file stops startup instead of producing a half-working service.

Check it worked

pytest prints a row of dots and 11 passed, with no warnings summary. The real predictions.log still has 5 lines, because the tests wrote to their own temporary log.

Step 8 · Stop the server and clean up

Press Ctrl+C in the second terminal. uvicorn runs the code after yield in lifespan, which closes the log file, and prints Application shutdown complete.

Then leave the virtual environment and remove the demo folder, including the model and the log:

Bash
deactivate
cd ~
rm -rf ~/churn-api-demo

When you deploy a service like this, run it behind a reverse proxy, keep the pinned versions in a requirements file next to the code, and remember that each extra uvicorn worker (--workers) loads its own copy of the model into memory.

Check it worked

ls ~/churn-api-demo reports that there is no such file or directory, and curl http://127.0.0.1:8000/healthz fails to connect.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.