Lab: A Validated Prediction API with Shared Batch Scoring
Build a FastAPI prediction service for a scikit-learn churn model saved with skops: a Pydantic schema that rejects bad input with a 422, liveness, readiness and version endpoints, a model loaded once at startup, and a batch scoring command that validates rows with the same schema and calls the same predict function, then prove that training, API and batch give identical predictions.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Train and export the artifact
- Step 2: One schema and one predict function
- Step 3: The API with health and version endpoints
- Step 4: Run the service for real
- Step 5: Batch scoring with the same code
- Step 6: Prove that all paths agree
- Check your understanding
- Apply it
- Review prompt
Lessons of Model Packaging & Serving
- What Exactly Are You Shipping? Model Artifacts and Formats Concept · 20 min
- Batch, Online or Streaming: Picking the Inference Pattern Concept · 15 min
- Lab: A Validated Prediction API with Shared Batch Scoring Lab · 30 min
- Lab: Containerize, Load-Test and Optimize Lab · 30 min
- Safe Rollouts: Shadow, Canary, A/B Tests and Rollback Concept · 15 min
- Check: Serving Design Review Knowledge check · 8 questions
What you will learn
- Serialize a model together with its preprocessing and metadata in a portable, safe format (for example skops or joblib with pinned versions, safetensors, ONNX) and verify that predictions match the training environment.
- Build an online inference API (for example with FastAPI) with input schema validation, health and version endpoints, plus a batch scoring job that reuses the same prediction code.
Prerequisites: Containerization
01. Goal and setup
You will serve one model in two ways. The online path is an HTTP API that scores customers on request. The batch path is a command that scores a CSV file of customers overnight. Both must validate their input with the same rules and compute predictions with the same code, because two copies of that logic drift apart and then give different answers for the same customer.
The service uses FastAPI, a Python web framework that reads type hints to validate requests, and Pydantic, the library that does the validation. The model is the churn pipeline from the artifacts lesson, saved with skops together with metadata. You need Python 3.12 and curl. Everything runs locally; the API listens on port 8741.
serving-lab/
├── data.py seeded churn data (as in the artifacts lesson)
├── train_export.py step 1: model.skops + metadata.json
├── predict.py step 2: the schema and the shared predict code
├── app.py step 3: the FastAPI service
├── check_api.py step 3: calls the API in-process
├── make_requests.py step 5: a batch input with two broken rows
├── score_batch.py step 5: the batch scoring command
└── parity.py step 6: training, API and batch comparedmkdir -p serving-lab && cd serving-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*" "skops==0.16.*" \
"fastapi==0.163.*" "uvicorn==0.54.*" "pydantic==2.14.*" "httpx2==2.16.*"02. Step 1: Train and export the artifact
train_export.py fits the preprocessing and the model as one pipeline and saves it with skops. Next to it, metadata.json records a model version name, the SHA-256 hash of the file, the scikit-learn version, the decision threshold and the predicted probabilities for five reference customers. The service will report the version and hash, and step 6 uses the reference probabilities to prove the service computes what training computed.
"""Seeded churn data: three numeric and two categorical columns."""
import numpy as np
import pandas as pd
NUMERIC = ["tenure_months", "monthly_fee", "support_calls"]
CATEGORICAL = ["plan", "channel"]
def make(n=4000, seed=0):
rng = np.random.default_rng(seed)
df = pd.DataFrame({
"tenure_months": rng.integers(0, 72, n),
"monthly_fee": rng.normal(45, 15, n).clip(5, 120).round(2),
"support_calls": rng.poisson(1.5, n),
"plan": rng.choice(["basic", "standard", "premium"], n, p=[0.5, 0.3, 0.2]),
"channel": rng.choice(["online", "store"], n, p=[0.7, 0.3]),
})
logit = (-1.0 - 0.04 * df.tenure_months + 0.03 * (df.monthly_fee - 45)
+ 0.45 * df.support_calls + 0.6 * (df.plan == "basic"))
df["churned"] = (rng.random(n) < 1 / (1 + np.exp(-logit))).astype(int)
return df"""Train the pipeline and save the artifact the service will load."""
import hashlib
import json
import numpy as np
import sklearn
import skops.io as sio
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from data import CATEGORICAL, NUMERIC, make
df = make()
model = Pipeline([
("prep", ColumnTransformer([
("num", StandardScaler(), NUMERIC),
("cat", OneHotEncoder(handle_unknown="ignore"), CATEGORICAL),
])),
("clf", LogisticRegression(max_iter=1000)),
]).fit(df[NUMERIC + CATEGORICAL], df["churned"])
sio.dump(model, "model.skops")
sample = df[NUMERIC + CATEGORICAL].head(5)
sample.to_csv("reference_rows.csv", index=False)
digest = hashlib.sha256(open("model.skops", "rb").read()).hexdigest()
metadata = {
"model_version": "churn-2026-11-16",
"sha256": digest,
"scikit_learn": sklearn.__version__,
"threshold": 0.5,
"reference_proba": np.round(model.predict_proba(sample)[:, 1], 6).tolist(),
}
json.dump(metadata, open("metadata.json", "w"), indent=2)
print("saved model.skops and metadata.json")
print("reference probabilities:", metadata["reference_proba"])python train_export.pysaved model.skops and metadata.json
reference probabilities: [0.097446, 0.070152, 0.0609, 0.182295, 0.37172]The hash is not printed because it changes every time you save: a skops file is a zip archive, and zip entries carry the time they were written. That is fine. The hash identifies the exact file you deploy, which is what you need during an incident, while the reference probabilities identify its behaviour.
03. Step 2: One schema and one predict function
predict.py is the heart of the lab, and the only file that touches the model. Customer is a Pydantic model: each field has a type and limits, Literal lists the allowed categories, and extra="forbid" turns unknown fields into errors instead of silently dropping them. The ranges are wide on purpose. They reject impossible values, such as a negative number of support calls, not merely unusual ones. Model.predict takes validated customers, builds the data frame with the column names the pipeline expects, and returns Prediction objects that carry the model version, so every answer can be traced to the artifact that produced it.
"""The one place that knows how to turn validated inputs into predictions."""
import json
from typing import Literal
import pandas as pd
import skops.io as sio
from pydantic import BaseModel, ConfigDict, Field
class Customer(BaseModel):
"""One request row. Pydantic rejects anything that does not fit these rules."""
model_config = ConfigDict(extra="forbid") # unknown fields are an error
tenure_months: int = Field(ge=0, le=600)
monthly_fee: float = Field(gt=0, le=1000)
support_calls: int = Field(ge=0, le=100)
plan: Literal["basic", "standard", "premium"]
channel: Literal["online", "store"]
class Prediction(BaseModel):
churn_probability: float
will_churn: bool
model_version: str
class Model:
def __init__(self, path="model.skops", metadata_path="metadata.json"):
self.metadata = json.load(open(metadata_path))
self.pipeline = sio.load(path) # only scikit-learn types inside
def predict(self, customers: list[Customer]) -> list[Prediction]:
frame = pd.DataFrame([c.model_dump() for c in customers])
proba = self.pipeline.predict_proba(frame)[:, 1]
version, threshold = self.metadata["model_version"], self.metadata["threshold"]
return [Prediction(churn_probability=round(float(p), 6),
will_churn=bool(p >= threshold), model_version=version)
for p in proba]04. Step 3: The API with health and version endpoints
app.py loads the model in the lifespan handler, code that FastAPI runs once when the process starts and once when it stops, so requests never pay the loading time. It exposes four endpoints:
GET /health/live, the liveness check: "the process is running and answers". A platform such as Kubernetes restarts the container when this fails.GET /health/ready, the readiness check: "this instance can serve predictions now". It returns 503 until the model is loaded, and the platform sends traffic only to ready instances.GET /version: which model, which file and which library version this instance serves.POST /predict: a list of customers in, a list of predictions out. FastAPI validates the body againstlist[Customer]before your function runs, and answers 422 Unprocessable Content with a description of every problem when it does not fit.
check_api.py calls the app in-process with FastAPI's TestClient, which sends real HTTP requests without opening a network port. Used without with, the client does not run the lifespan, which lets you see the service before its model is loaded.
"""Online inference: a FastAPI service around the shared predict module."""
from contextlib import asynccontextmanager
from fastapi import FastAPI, Response
from predict import Customer, Model, Prediction
state = {"model": None}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["model"] = Model() # load once, at startup
yield
state["model"] = None
app = FastAPI(title="churn-api", lifespan=lifespan)
@app.get("/health/live")
def live():
return {"status": "alive"} # the process answers: do not restart it
@app.get("/health/ready")
def ready(response: Response):
if state["model"] is None: # not loaded: send no traffic here yet
response.status_code = 503
return {"status": "loading"}
return {"status": "ready"}
@app.get("/version")
def version():
meta = state["model"].metadata
return {"model_version": meta["model_version"], "sha256": meta["sha256"][:12],
"scikit_learn": meta["scikit_learn"]}
@app.post("/predict")
def predict(customers: list[Customer]) -> list[Prediction]:
return state["model"].predict(customers)"""Call the API in-process with FastAPI's TestClient, before and after startup."""
import json
from fastapi.testclient import TestClient
from app import app
good = {"tenure_months": 3, "monthly_fee": 70.0, "support_calls": 4,
"plan": "basic", "channel": "online"}
client = TestClient(app) # no "with": the startup has not run
print("before startup:", client.get("/health/live").status_code,
client.get("/health/ready").status_code, client.get("/health/ready").json())
with TestClient(app) as client: # "with" runs the lifespan: model loads
print("after startup: ", client.get("/health/ready").json())
info = client.get("/version").json()
print("version:", info["model_version"], "| scikit-learn", info["scikit_learn"])
loyal = dict(good, tenure_months=60, plan="premium")
r = client.post("/predict", json=[good, loyal])
print(r.status_code)
for prediction in r.json():
print(" ", json.dumps(prediction, separators=(",", ":")))
bad = dict(good, support_calls=-2, plan="gold", discount=0.1)
r = client.post("/predict", json=[bad])
print(r.status_code)
for error in r.json()["detail"]:
print(" ", error["loc"], "-", error["msg"])python check_api.pybefore startup: 200 503 {'status': 'loading'}
after startup: {'status': 'ready'}
version: churn-2026-11-16 | scikit-learn 1.9.1
200
{"churn_probability":0.885296,"will_churn":true,"model_version":"churn-2026-11-16"}
{"churn_probability":0.256813,"will_churn":false,"model_version":"churn-2026-11-16"}
422
['body', 0, 'support_calls'] - Input should be greater than or equal to 0
['body', 0, 'plan'] - Input should be 'basic', 'standard' or 'premium'
['body', 0, 'discount'] - Extra inputs are not permittedBefore startup the process is alive (200) but not ready (503), which is exactly the state in which a platform should keep traffic away. After startup the predictions carry the model version. The broken request gets one 422 with three precise errors: a value below its limit, a category the model does not know and a field nobody asked for. Each error names its location, body → item 0 → field, so the caller knows what to fix. Without the schema, the same request would reach the pipeline, where gold becomes an all-zero one-hot vector and -2 a valid-looking number, and the client would get a confident but meaningless probability.
05. Step 4: Run the service for real
Uvicorn is the server that runs a FastAPI app. Start it in a second terminal, in the lab folder with the virtual environment active, and leave it running. Then call it with curl from the first terminal.
uvicorn app:app --host 127.0.0.1 --port 8741curl -s http://127.0.0.1:8741/health/ready; echo
curl -s -X POST http://127.0.0.1:8741/predict -H "Content-Type: application/json" \
-d '[{"tenure_months": 3, "monthly_fee": 70.0, "support_calls": 4,
"plan": "basic", "channel": "online"}]'; echo
curl -s -o /dev/null -w "%{http_code}\n" -X POST http://127.0.0.1:8741/predict \
-H "Content-Type: application/json" -d '[{"tenure_months": "three"}]'{"status":"ready"}
[{"churn_probability":0.885296,"will_churn":true,"model_version":"churn-2026-11-16"}]
422The service is ready, the prediction matches the one from check_api.py, and a body with a text tenure and missing fields is refused with 422. FastAPI also generates interactive documentation for every endpoint and schema at http://127.0.0.1:8741/docs. Leave the server running for now; stop it with Ctrl+C at the end of the lab.
06. Step 5: Batch scoring with the same code
make_requests.py writes tonight's input: 1,000 customers with an id column, one of them with the text unknown as its fee and one with a plan the model has never seen. score_batch.py reads the CSV, validates every row with the same Customer schema, scores the valid rows with the same Model.predict and writes two files: the predictions, and a rejects file with the reason for each refused row. CSV values arrive as text; Pydantic's default lax mode converts text such as "12" to the declared number type, and refuses text that is not a number.
"""Write tonight's batch input: 1,000 customers, two of them broken."""
from data import CATEGORICAL, NUMERIC, make
rows = make(n=1000, seed=7)[NUMERIC + CATEGORICAL]
rows["monthly_fee"] = rows["monthly_fee"].astype(object)
rows.loc[10, "monthly_fee"] = "unknown" # a text value in a number column
rows.loc[20, "plan"] = "gold" # a plan the model has never seen
rows.insert(0, "customer_id", [f"C{i:04d}" for i in range(len(rows))])
rows.to_csv("customers.csv", index=False)
print(f"wrote customers.csv with {len(rows)} rows")"""Batch inference: validate every row, score the valid ones, keep the rejects."""
import csv
import sys
from pydantic import ValidationError
from predict import Customer, Model
source, target = sys.argv[1], sys.argv[2]
model = Model()
valid, ids, rejects = [], [], []
with open(source, newline="") as f:
for row in csv.DictReader(f):
customer_id = row.pop("customer_id")
try:
valid.append(Customer.model_validate(row)) # the same rules as the API
ids.append(customer_id)
except ValidationError as error:
first = error.errors()[0]
rejects.append([customer_id, first["loc"][0], first["msg"]])
predictions = model.predict(valid)
with open(target, "w", newline="") as f:
out = csv.writer(f)
out.writerow(["customer_id", "churn_probability", "will_churn", "model_version"])
for customer_id, p in zip(ids, predictions):
out.writerow([customer_id, p.churn_probability, p.will_churn, p.model_version])
with open("rejects.csv", "w", newline="") as f:
csv.writer(f).writerows([["customer_id", "field", "error"]] + rejects)
print(f"scored {len(predictions)} rows, rejected {len(rejects)} (see rejects.csv)")python make_requests.py
python score_batch.py customers.csv predictions.csvwrote customers.csv with 1000 rows
scored 998 rows, rejected 2 (see rejects.csv)cat rejects.csv; echo; head -3 predictions.csvcustomer_id,field,error
C0010,monthly_fee,"Input should be a valid number, unable to parse string as a number"
C0020,plan,"Input should be 'basic', 'standard' or 'premium'"
customer_id,churn_probability,will_churn,model_version
C0000,0.025836,False,churn-2026-11-16
C0001,0.082011,False,churn-2026-11-16The job scored 998 rows and set two aside with a precise reason, instead of crashing on the first bad row or, worse, scoring unknown as a number. A batch job serves many customers at once, so one broken record should not cost everyone their predictions; but the rejects must be counted and someone must look at them. In production you would also fail the whole job when the share of rejects passes a limit, because many rejects at once usually mean a broken upstream source rather than a few bad rows.
07. Step 6: Prove that all paths agree
The last script sends the five reference customers through the API and through the batch command, and compares both with the probabilities that train_export.py stored at training time.
"""Do the API, the batch job and the training run agree on the same customers?"""
import csv
import json
import subprocess
import sys
from fastapi.testclient import TestClient
from app import app
reference = json.load(open("metadata.json"))["reference_proba"] # from training
with open("reference_rows.csv", newline="") as f:
rows = list(csv.DictReader(f))
with TestClient(app) as client: # the online path
api = [p["churn_probability"] for p in client.post("/predict", json=rows).json()]
with open("reference_batch.csv", "w", newline="") as f: # the batch path
writer = csv.DictWriter(f, fieldnames=["customer_id", *rows[0]])
writer.writeheader()
writer.writerows({"customer_id": f"R{i}", **row} for i, row in enumerate(rows))
subprocess.run([sys.executable, "score_batch.py", "reference_batch.csv",
"reference_scores.csv"], check=True, capture_output=True)
with open("reference_scores.csv", newline="") as f:
batch = [float(r["churn_probability"]) for r in csv.DictReader(f)]
print("training:", reference)
print("API: ", api)
print("batch: ", batch)
print("all three agree:", reference == api == batch)python parity.pytraining: [0.097446, 0.070152, 0.0609, 0.182295, 0.37172]
API: [0.097446, 0.070152, 0.0609, 0.182295, 0.37172]
batch: [0.097446, 0.070152, 0.0609, 0.182295, 0.37172]
all three agree: TrueAll three agree to every printed digit, and they do so because there is one schema, one predict function and one artifact. Keep parity.py as a test: run it in CI and after every deployment, and a change to either path that alters predictions fails loudly.
08. Check your understanding
09. Apply it
For your project, serve the model you packaged in the artifacts lesson. Write its Customer-style schema from your metadata (types, limits, categories, extra="forbid"), one predict module, the four endpoints and a batch command that reuses both. Add parity.py and a rejects limit to your tests. In the next lab you will put this service in a container, load-test it and optimise it.
10. Review prompt
Without looking back, answer in your own words:
- What do the liveness, readiness and version endpoints each tell a platform or an engineer?
- What does FastAPI do with a request body that does not match the schema, and what does the client receive?
- Why must the API and the batch job share one schema and one predict function?
- How does
parity.pyprove that serving computes what training computed?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.