Rana Maninder Singh
Lesson 3 of 8MLOps

Serving with FastAPI

Lesson opener

In one line: Building a REST API with FastAPI to serve churn predictions.

Why it matters: APIs decouple the model from the client. Any team can consume them without installing scikit-learn.

Before this lesson: Saving models & reproducible environments / Docker Desktop install

Before you start


What you will learn

  • Building a REST API with FastAPI to serve churn predictions
  • Using Pydantic models to validate incoming request data offline
  • Shaping /predict and /health JSON payloads before you start uvicorn
  • Pinning FastAPI / Pydantic / Uvicorn for reproducible serving
  • Adding health checks and rejecting bad feature payloads early

Why serve a model as an API

The stakeholder's app needs predictions, not a .pkl file. An API endpoint (POST /predict) returns a JSON response the frontend can display in milliseconds. Retention dashboards in Indian product orgs usually call this from a Node or Flutter client — the model stays behind the API boundary.

WHY APIs decouple the model from the client. Any team can consume them without installing scikit-learn.

WHEN The model needs to serve live requests — CRM sidebars, batch scorers behind a gateway, or internal tools that must not share pickle files.

This course pins serving deps in docs/mlops/requirements.txt:

Official docs: FastAPI, Pydantic, Uvicorn.

What the API owns vs what the client owns

ConcernOwnerWhy
Feature validation (ge=0, required fields)API (Pydantic)One gate; every client benefits
Ranking / top-50 selectionClient or batch jobCapacity policy is a product rule
Model bytes / pinsServing imageClients never pip install sklearn
Auth / rate limitsGateway or hostKeep the FastAPI app focused

WHY validate before uvicorn: Most serving bugs are bad JSON, not bad forests. Practising Pydantic offline means you can unit-test 422-shaped failures in CI without opening a port.

WHEN /health must go degraded: Return degraded (not a hard process crash) when the model file is missing or failed to load. A Bengaluru on-call should see model_loaded: false in the health payload and know to check MODEL_PATH — not dig through a stack trace from /predict.

Failure modes at the HTTP boundary

  1. Missing field — frontend omits support_tickets → Pydantic 422, not a sklearn crash.
  2. Negative tenure — bad ETL → rejected at Field(ge=0).
  3. Feature order mismatch — train used [tenure, spend, tickets] but serve builds a different order → silent wrong scores. Keep one shared feature list constant.
  4. Eager load in serverless — cold start loads the pickle on every invoke → timeouts. Lazy-init for serverless; startup load for long-running containers.
  5. No /health — free host marks the service healthy while the model path is wrong.

Indian workplace framing: call-centre tools often sit behind flaky office networks. Prefer clear JSON errors over opaque 500s so a support engineer in a different city can fix the payload without paging the ML author.

Validate features before the server exists

You do not need uvicorn running to practice request validation. Pydantic models raise ValidationError on bad input — that is the same gate FastAPI uses for 422 responses.

Runnable: Pydantic Features model

from pydantic import BaseModel, ValidationError, Field

class Features(BaseModel):
    tenure_months: int = Field(ge=0)
    monthly_spend: float = Field(ge=0)
    support_tickets: int = Field(ge=0)

ok = Features(tenure_months=30, monthly_spend=5000.0, support_tickets=2)
assert ok.tenure_months == 30
print("valid:", ok.model_dump())

try:
    Features(tenure_months=-1, monthly_spend=5000, support_tickets=2)
    raise AssertionError("expected ValidationError")
except ValidationError as exc:
    print("rejected negative tenure:", exc.error_count(), "error(s)")

Runnable: validation test cases for churn features

from pydantic import BaseModel, ValidationError, Field

class Features(BaseModel):
    tenure_months: int = Field(ge=0)
    monthly_spend: float = Field(ge=0)
    support_tickets: int = Field(ge=0)

cases = [
    ({"tenure_months": 12, "monthly_spend": 499, "support_tickets": 1}, True),
    ({"tenure_months": 0, "monthly_spend": 0, "support_tickets": 0}, True),
    ({"tenure_months": -3, "monthly_spend": 100, "support_tickets": 0}, False),
    ({"tenure_months": 5, "monthly_spend": -10, "support_tickets": 0}, False),
    ({"tenure_months": 5, "monthly_spend": 100}, False),  # missing field
]

passed = 0
for payload, should_pass in cases:
    try:
        Features(**payload)
        ok = True
    except ValidationError:
        ok = False
    assert ok is should_pass, payload
    passed += 1

print(f"feature validation cases passed: {passed}/{len(cases)}")

Runnable: health payload dict (contract for /health)

def health_payload(model_loaded: bool, version: str = "1.0") -> dict:
    status = "ok" if model_loaded else "degraded"
    return {"status": status, "version": version, "model_loaded": model_loaded}

healthy = health_payload(True)
assert healthy == {"status": "ok", "version": "1.0", "model_loaded": True}
degraded = health_payload(False, version="1.1")
assert degraded["status"] == "degraded"
print("health contracts:", healthy, degraded)

Minimal FastAPI serving app

The app below is the production shape. It is tagged # requires: server because it loads a model file and expects a long-running process — practice validation with the offline blocks above first.

# requires: server
from fastapi import FastAPI
from pydantic import BaseModel, Field
import joblib

app = FastAPI(title="Churn Predictor", version="1.0")
model = joblib.load("models/churn_model_v1.pkl")

class Features(BaseModel):
    tenure_months: int = Field(ge=0)
    monthly_spend: float = Field(ge=0)
    support_tickets: int = Field(ge=0)

@app.post("/predict")
def predict(features: Features):
    X = [[features.tenure_months, features.monthly_spend, features.support_tickets]]
    prediction = model.predict(X)[0]
    probability = model.predict_proba(X)[0].tolist()
    return {"churn": bool(prediction), "probability": probability}

@app.get("/health")
def health():
    return {"status": "ok", "version": "1.0", "model_loaded": True}
uvicorn app:app --host 0.0.0.0 --port 8000 --reload

[!important] Never load the model at import time in a serverless function — use a lazy init. For a long-running container, loading once at startup is fine.


Testing the endpoint

curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"tenure_months": 30, "monthly_spend": 5000, "support_tickets": 2}'

Expected shape: {"churn": true, "probability": [0.2, 0.8]} (exact numbers depend on the trained model).

For a Bengaluru retention dashboard, reject incomplete JSON early so the frontend can show "missing support_tickets" instead of a 500 from the model layer.

WHY predict_proba for capacity-limited saves

The call centre can only contact 50 customers per week. A boolean churn flag is not enough: you need ranked probabilities so the CRM or batch job can take the top 50. Returning both churn and probability lets product choose the threshold later without redeploying the model for every policy tweak.

WHEN to keep the API thin: Do not encode “top 50” inside FastAPI unless every consumer agrees. Capacity is a business rule — different regions or campaigns may use 30 or 100. Serve scores; let the consumer apply the cap.

Contract checklist before you wire the UI

  1. POST /predict accepts the three churn features and rejects negatives / missing keys.
  2. Response always includes churn (bool) and probability (length-2 list for binary class).
  3. GET /health returns status, version, and model_loaded.
  4. Serving image installs the same pins as training (docs/mlops/requirements.txt).
  5. Feature column order matches training — document it next to the pickle name.

Failure mode — “it works in curl, fails in the app”

Usually a content-type or field-name mismatch (monthlySpend vs monthly_spend). Fix the client schema; do not loosen Pydantic to accept anything. Loose validation is how wrong spend units (₹ vs paise) reach the forest and scramble the weekly list.

Runnable: probability ranking for the weekly save list

FastAPI should return probabilities; the consumer takes the top 50. Practice the ranking offline.

# Offline demo: rank customers by churn probability for a capacity cap
scored = [
    {"id": "A", "p": 0.12},
    {"id": "B", "p": 0.81},
    {"id": "C", "p": 0.55},
]


def top_ids(rows: list[dict], cap: int) -> list[str]:
    return [r["id"] for r in sorted(rows, key=lambda x: x["p"], reverse=True)[:cap]]


assert top_ids(scored, 2) == ["B", "C"]
print(top_ids(scored, 2))

Runnable: reject negative feature payloads before predict

Mirror the Pydantic Field(ge=0) rule with a plain function you can unit-test without uvicorn.

# Offline demo: reject negative churn features the way the API should
def valid_features(tenure: int, spend: float, tickets: int) -> bool:
    return tenure >= 0 and spend >= 0 and tickets >= 0


assert valid_features(30, 5000, 2) is True
assert valid_features(-1, 5000, 2) is False
print("valid", valid_features(10, 99.0, 0))


Verified against scikit-learn 1.5.2, pandas 2.2.3, numpy 2.1.3 (+6 more) documentation, September 2026.

Test yourself

  1. What command starts a FastAPI app with uvicorn?
  2. What decorator defines a POST endpoint in FastAPI?
  3. What does Pydantic validate automatically?
  4. What HTTP status code does FastAPI return for validation errors?
  5. Name the request body model class in the example above.
  6. What does @app.get("/health") define?
  7. Why is predict_proba better than predict alone for call-centre prioritisation?
  8. What does --reload do in uvicorn?
  9. What is the input format for /predict?
  10. True or false: FastAPI uses type hints / Pydantic models for request bodies.

What's next

Docker for ML