A Prediction Service with FastAPI
The previous lesson argued that some predictions must be made while a client waits: a checkout page, a loan form, another service. Those clients are written in JavaScript, Java or Go, not in Python, and they will never import your pipeline. They speak HTTP and JSON. So the model needs a thin layer around it that accepts an HTTP request, checks the JSON, turns it into the model's input, calls the model and returns JSON: a prediction service.
FastAPI is the most common Python framework for this. You write ordinary Python functions, declare the shape of the request and response with Pydantic models (the signature as code), and FastAPI handles parsing, validation, error responses and an OpenAPI description of the API. This lesson builds the risk-model service step by step, and every example runs in your browser.
How the examples run in the browser
A real service runs under an ASGI server such as Uvicorn (uvicorn main:app --port 8000), which listens on a network port and passes each HTTP request to the app. A browser tab cannot open a listening port, but it does not need one: an ASGI app is just an async callable, and the httpx client can call it directly through httpx.ASGITransport. The request goes through exactly the same routing, validation and serialisation as over the network.
One browser-specific rule: write every endpoint as async def. FastAPI runs plain def endpoints in a thread pool so that they do not block the server; that is the normal choice on a real server for blocking code, but the browser's Python has no threads. A quick model call such as a logistic regression on one row takes microseconds, so an async def endpoint that calls it directly is fine on a server too. (A long CPU-bound call inside async def would block the event loop; on a real server you would then use def or a worker pool, as the production lesson discusses.)
The smallest service
An app, one route, one client call:
import asyncio, httpx
from fastapi import FastAPI
app = FastAPI(title="risk-model")
@app.get("/health")
async def health():
return {"status": "ok"}
async def main():
transport = httpx.ASGITransport(app=app)
async with httpx.AsyncClient(transport=transport, base_url="http://test") as client:
r = await client.get("/health")
print(r.status_code, r.headers["content-type"], r.json())
r = await client.get("/nothing-here")
print(r.status_code, r.json())
asyncio.run(main())200 application/json {'status': 'ok'}
404 {'detail': 'Not Found'}
@app.get("/health") registers the function for GET /health; the returned dictionary becomes the JSON body. An unknown path gets a 404 with a JSON error, without any code on your side.
A predict endpoint with request and response models
Now the real thing. The model is trained (in a real service: loaded from the artifact) once, when the module is imported, not inside the endpoint. The request body is a Pydantic model with the eight features and their domain rules, the response model fixes what the client gets back. FastAPI reads the JSON body into LoanApplication, so the endpoint receives a validated object, and it serialises the return value through RiskPrediction, so the response can only contain the declared fields.
import asyncio, httpx
import numpy as np
from fastapi import FastAPI
from pydantic import BaseModel, Field
from sklearn.datasets import make_classification
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
FEATURES = ["income", "debt_ratio", "age", "years_employed", "num_accounts",
"late_payments", "credit_utilisation", "loan_amount"]
X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
MODEL = make_pipeline(StandardScaler(), LogisticRegression()).fit(X, y) # once, at start-up
MODEL_VERSION = "3"
class LoanApplication(BaseModel):
income: float
debt_ratio: float
age: float
years_employed: float
num_accounts: float
late_payments: float
credit_utilisation: float
loan_amount: float
class RiskPrediction(BaseModel):
p_default: float = Field(ge=0, le=1)
decision: str
model_version: str
app = FastAPI(title="risk-model")
@app.post("/predict", response_model=RiskPrediction)
async def predict(app_in: LoanApplication):
row = np.array([[getattr(app_in, f) for f in FEATURES]]) # columns by name, in the model's order
p = float(MODEL.predict_proba(row)[0, 1])
return RiskPrediction(p_default=round(p, 4), decision="review" if p >= 0.5 else "approve",
model_version=MODEL_VERSION)
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
for i in (0, 1):
body = dict(zip(FEATURES, X[i].round(3).tolist()))
r = await client.post("/predict", json=body)
print(r.status_code, r.json(), "| true label", int(y[i]))
asyncio.run(main())200 {'p_default': 0.9974, 'decision': 'review', 'model_version': '3'} | true label 1
200 {'p_default': 0.0892, 'decision': 'approve', 'model_version': '3'} | true label 0
The client sent plain JSON objects and got back a probability, a decision and the model version: 0.9974 ("review") for the first row and 0.0892 ("approve") for the second. These two rows were part of the training data, so this only shows that the plumbing works, not how good the model is (that was measured on a holdout in the artifact lesson). Returning the model version with every prediction costs nothing and makes every logged prediction traceable to a model.
Validation errors: 422 before your code runs
If the JSON does not match the request model, FastAPI answers 422 Unprocessable Content with a detail list, one entry per problem, and the endpoint is never called. That protects the model from the classic bad inputs: a missing field, a string where a number belongs, a value outside the allowed range. Domain rules are declared on the fields:
import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel, Field
class LoanApplication(BaseModel):
income: float = Field(gt=0)
age: int = Field(ge=18, le=100)
debt_ratio: float = Field(ge=0, le=5)
app = FastAPI()
calls = []
@app.post("/predict")
async def predict(a: LoanApplication):
calls.append(a)
return {"ok": True}
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
cases = {
"valid": {"income": 3200, "age": 37, "debt_ratio": 0.4},
"number as string": {"income": "3200", "age": 37, "debt_ratio": 0.4},
"missing age": {"income": 3200, "debt_ratio": 0.4},
"bad values": {"income": -5, "age": "old", "debt_ratio": 9},
}
for name, body in cases.items():
r = await client.post("/predict", json=body)
errors = [(e["loc"][-1], e["type"]) for e in r.json().get("detail", [])]
print(f"{name:17s} {r.status_code} {errors if errors else r.json()}")
r = await client.post("/predict", content="not json", headers={"content-type": "application/json"})
print(f"{'broken JSON':17s} {r.status_code} {r.json()['detail'][0]['type']}")
print("endpoint was called", len(calls), "times")
asyncio.run(main())valid 200 {'ok': True}
number as string 200 {'ok': True}
missing age 422 [('age', 'missing')]
bad values 422 [('income', 'greater_than'), ('age', 'int_parsing'), ('debt_ratio', 'less_than_equal')]
broken JSON 422 json_invalid
endpoint was called 2 times
Only the two valid requests reached the endpoint. Each error names the field and a stable error type (missing, greater_than, int_parsing, …) that a client can handle in code; a real response also carries a human-readable msg. Note the second case: by default Pydantic converts the string "3200" to the number 3200.0 ("lax mode"). That is convenient for clients that send numbers as strings, but it also hides sloppy clients. For a strict contract use Field(strict=True) or model_config = ConfigDict(strict=True) on the model.
Path and query parameters
Not everything is a JSON body. Path parameters identify a resource (/models/{name}), query parameters are options (?explain=true). FastAPI reads both from the function signature: a name that appears in the path is a path parameter, a simple-typed argument that does not is a query parameter, and both are converted and validated by their type annotations.
import asyncio, httpx
from fastapi import FastAPI, HTTPException, Query
REGISTRY = {"risk-model": {"versions": ["1", "2", "3"], "stage": "production"},
"churn-model": {"versions": ["1"], "stage": "staging"}}
app = FastAPI()
@app.get("/models/{name}")
async def model_info(name: str, versions: bool = False, limit: int = Query(10, ge=1, le=100)):
if name not in REGISTRY:
raise HTTPException(status_code=404, detail=f"unknown model '{name}'")
info = {"name": name, "stage": REGISTRY[name]["stage"]}
if versions:
info["versions"] = REGISTRY[name]["versions"][-limit:]
return info
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
for url in ("/models/risk-model", "/models/risk-model?versions=true&limit=2",
"/models/fraud-model", "/models/risk-model?limit=0"):
r = await client.get(url)
body = r.json()
if r.status_code == 422:
body = [(e["loc"], e["type"]) for e in body["detail"]]
print(r.status_code, url, body)
asyncio.run(main())200 /models/risk-model {'name': 'risk-model', 'stage': 'production'}
200 /models/risk-model?versions=true&limit=2 {'name': 'risk-model', 'stage': 'production', 'versions': ['2', '3']}
404 /models/fraud-model {'detail': "unknown model 'fraud-model'"}
422 /models/risk-model?limit=0 [(['query', 'limit'], 'greater_than_equal')]
HTTPException is how an endpoint returns an error on purpose; its detail becomes the JSON body. Use the status codes clients expect: 404 for an unknown resource, 422 for invalid input (FastAPI does that), 503 when the model is not ready, 500 only for real bugs.
The OpenAPI description for free
From the routes and Pydantic models, FastAPI generates an OpenAPI document (served at /openapi.json, with interactive docs at /docs on a real server). Other teams generate client code from it, and a contract test in CI can compare it with the previous version to catch breaking changes.
import asyncio, httpx
from fastapi import FastAPI
from pydantic import BaseModel, Field
class LoanApplication(BaseModel):
income: float = Field(gt=0)
age: int = Field(ge=18, le=100)
class RiskPrediction(BaseModel):
p_default: float
model_version: str
app = FastAPI(title="risk-model", version="3.0.0")
@app.post("/predict", response_model=RiskPrediction)
async def predict(a: LoanApplication):
return RiskPrediction(p_default=0.1, model_version="3")
async def main():
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
spec = (await client.get("/openapi.json")).json()
print(spec["info"])
for path, ops in spec["paths"].items():
for method, op in ops.items():
print(method.upper(), path, "->", list(op["responses"]))
print("LoanApplication.age:", spec["components"]["schemas"]["LoanApplication"]["properties"]["age"])
asyncio.run(main()){'title': 'risk-model', 'version': '3.0.0'}
POST /predict -> ['200', '422']
LoanApplication.age: {'type': 'integer', 'maximum': 100.0, 'minimum': 18.0, 'title': 'Age'}
The schema already documents the 422 response and carries the field limits (minimum: 18, maximum: 100) from the Pydantic model, so the documentation cannot drift from the validation.
Pitfalls
- Loading the model inside the endpoint. Every request would read the file again. Load once, at start-up.
- Building the input from the payload's field order. Take the features by name in the model's order (
FEATURES), as the predict endpoint does. - Returning raw NumPy types.
np.float64and arrays need converting (float(p),.tolist()); a response model makes the output explicit. - Long CPU work in
async defon a real server. It blocks every other request on that worker; keep model calls short or run them in a pool. - Treating 422 as a server error. It is the client's mistake; count it separately in monitoring, a spike usually means a client release broke the contract.
Practice
- Add a field
employment_type: strto the request that may only be"employed","self-employed"or"unemployed". Which Python type does that most simply? - A client sends
{"income": "3,200", ...}. What status code does the service return, and does the model see the request? - Why should
/predictbePOSTand notGET?
Answers
employment_type: Literal["employed", "self-employed", "unemployed"](fromtyping), or anEnum. Other values give a 422 with typeliteral_error(orenum).- 422:
"3,200"cannot be parsed as a float, even in lax mode. The endpoint, and therefore the model, is never called. - The input is a structured body with possibly sensitive data;
GETrequests carry data in the URL (logged by proxies, length-limited) and should not have bodies. A prediction also may be logged or audited, which is not the "safe, cacheable read" semantics ofGET.
Test yourself
What does FastAPI do when a request body does not match the endpoint's Pydantic model?
- Calls the endpoint with None values
- Returns 422 with a list of validation errors, without calling the endpoint
- Returns 500
- Silently drops the invalid fields
Why are all endpoints in these browser examples written as async def?
- FastAPI requires it everywhere
- Sync
defendpoints run in a thread pool, and the browser's Python (Pyodide) has no threads - Async endpoints are always faster
- httpx only supports async functions
In @app.get("/models/{name}") with async def f(name: str, versions: bool = False), what is versions?
- A path parameter
- A query parameter, e.g.
?versions=true - A request body
- A header
Where should the model be loaded in a FastAPI service?
- Inside each endpoint call
- Once at start-up, then reused by every request
- In the client
- In the response model