This is Module 4 of the Machine Learning Engineer path. In Module 2 you built a churn pipeline and saved it as one file. Now something needs to call it: a website, a CRM, a nightly report. This module turns the pipeline into a small service you can deploy, trace and test.

You’ll build: a versioned model file with a record of what it is, an HTTP API that validates input and logs every prediction, and tests for it.

You need: Python with scikit-learn, pandas, joblib, FastAPI, uvicorn, httpx and pytest (pip install scikit-learn pandas joblib fastapi uvicorn httpx pytest), and customers.csv from Module 2’s make_data.py.

1. Save the model with its facts

A file called model.joblib tells you nothing six months later. Give each trained model a version, and save a short record next to it. Save this as train.py:

# Train the Module 2 pipeline and save it with the facts you'll need later: version, data, features, score.
import json
from datetime import date

import joblib
import pandas as pd
import sklearn
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler

VERSION = "churn-2026-11-30.1"
NUMERIC = ["tenure_months", "support_tickets", "monthly_spend"]
CATEGORICAL = ["plan"]

df = pd.read_csv("customers.csv")
X, y = df[NUMERIC + CATEGORICAL], df["churned"]
model = Pipeline([
    ("prep", ColumnTransformer([
        ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), NUMERIC),
        ("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
    ])),
    ("clf", LogisticRegression(max_iter=1000)),
])
auc = cross_val_score(model, X, y, cv=5, scoring="roc_auc").mean()
model.fit(X, y)

joblib.dump(model, f"{VERSION}.joblib")
card = {"version": VERSION, "trained_on": str(date.today()), "rows": len(df), "features": NUMERIC + CATEGORICAL,
        "cv_roc_auc": round(auc, 3), "sklearn": sklearn.__version__}
with open(f"{VERSION}.json", "w") as f:
    json.dump(card, f, indent=2)
print(json.dumps(card))
{"version": "churn-2026-11-30.1", "trained_on": "2026-11-30", "rows": 2000, "features": ["tenure_months", "support_tickets", "monthly_spend", "plan"], "cv_roc_auc": 0.761, "sklearn": "1.9.1"}

The record answers the questions people ask when a prediction looks wrong: which model made it, trained on what, how good it was, and with which library version (a model saved with one scikit-learn version isn’t guaranteed to load correctly in another).

2. Serve it behind a small API

Save this as serve.py:

# A small prediction API: validates input, scores it with the saved pipeline, logs every request.
import json
import time
import uuid
from typing import Optional

import joblib
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field

VERSION = "churn-2026-11-30.1"
model = joblib.load(f"{VERSION}.joblib")
app = FastAPI()


class Customer(BaseModel):
    plan: str
    tenure_months: int = Field(ge=0, le=600)
    support_tickets: int = Field(ge=0)
    monthly_spend: Optional[float] = Field(default=None, ge=0)


@app.post("/predict")
def predict(c: Customer) -> dict:
    p = float(model.predict_proba(pd.DataFrame([c.model_dump()]))[0, 1])
    out = {"churn_probability": round(p, 4), "model_version": VERSION, "request_id": str(uuid.uuid4())}
    # Log inputs and output together, so production data can be checked against training data later.
    with open("predictions.jsonl", "a") as f:
        f.write(json.dumps({"ts": time.time(), "input": c.model_dump(), **out}) + "\n")
    return out

Three decisions are built in:

  • Validation before scoring. The Customer model rejects impossible inputs, such as negative tenure, before the pipeline sees them. Missing spend is allowed, because the pipeline’s imputer handles it.
  • The version travels with every answer, so a caller can report exactly which model produced a prediction.
  • Every request is logged with its prediction. This is Rule #29 of Google’s Rules of Machine Learning: “save the set of features used at serving time, and then pipe those features to a log to use them at training time.” The log is how you’ll later detect that production data has drifted away from training data (Module 5).

Run it with uvicorn serve:app --port 8765 and call it:

curl -s -X POST localhost:8765/predict -H 'Content-Type: application/json' \
  -d '{"plan": "pro", "tenure_months": 3, "support_tickets": 4, "monthly_spend": 52.0}'
{"churn_probability":0.636,"model_version":"churn-2026-11-30.1","request_id":"d60ef3f5-951d-4532-8fe1-0221771807f1"}

The same call with "tenure_months": -5 returns HTTP 422, FastAPI’s validation error, instead of a prediction. Your request ID will differ.

3. Test it like software

FastAPI’s TestClient calls the app directly, without starting a server, so tests run in about a second. Save this as test_serve.py and run pytest test_serve.py:

# Run with: pytest test_serve.py
import json
import os

from fastapi.testclient import TestClient

from serve import app

client = TestClient(app)


def test_known_customer_scores_as_recorded():
    r = client.post("/predict", json={"plan": "pro", "tenure_months": 3, "support_tickets": 4, "monthly_spend": 52.0})
    assert r.status_code == 200
    assert abs(r.json()["churn_probability"] - 0.64) < 0.01
    assert r.json()["model_version"] == "churn-2026-11-30.1"


def test_bad_input_is_rejected_not_scored():
    r = client.post("/predict", json={"plan": "pro", "tenure_months": -5, "support_tickets": 1})
    assert r.status_code == 422


def test_every_prediction_is_logged_with_its_input():
    before = os.path.getsize("predictions.jsonl") if os.path.exists("predictions.jsonl") else 0
    client.post("/predict", json={"plan": "basic", "tenure_months": 40, "support_tickets": 0})
    with open("predictions.jsonl") as f:
        f.seek(before)
        row = json.loads(f.readline())
    assert row["input"]["plan"] == "basic" and "churn_probability" in row
3 passed

Depending on library versions, pytest may also print a deprecation warning from the test client; it doesn’t affect the results. The first test is the golden record from Module 2, now checked through the API. The second proves bad input is refused. The third proves the log contains what you’ll need later.

4. API or batch job?

An API isn’t always the right shape. Choose by how fresh predictions must be:

HTTP API Scheduled batch job
Use when A prediction is needed during a request: checkout, sign-up, a support chat A list is needed by a time: tomorrow’s at-risk customers
Runs Always on Once a day or hour
Main risks Latency, uptime, bad input from callers A failed run nobody notices
Logging Each request Each run: input file, model version, row count

For a churn model used by a retention team each morning, a nightly batch job that writes a scored CSV is simpler, cheaper and easier to check. Reach for the API when a product needs an answer in the moment.

A checklist before you ship

  • The model file has a version, and a record of its training data, features, score and library version.
  • Inputs are validated, with deliberate rules for missing values.
  • Every prediction is logged with its inputs and model version.
  • Tests cover a golden record, bad input and logging, and run in CI.
  • You’ve chosen API or batch on purpose.

Project

Serve your own Module 2 pipeline behind this API. Add a /health endpoint that returns the model version, write the batch alternative that scores a CSV, and add a test for each.

Next: Module 5: Monitoring, Drift and Retraining, using what you logged to catch a changing world before it costs you.