What You Will Build
A model that only answers Python function calls can be used by one program
on one computer. To be a service, it needs an interface that other programs
can call over the network with a well-defined input and output. In this
lesson you wrap the practice model in an HTTP API with FastAPI: one
endpoint, POST /predict, that accepts six readings as JSON, validates them,
and returns the prediction as JSON. You run it with uvicorn on
127.0.0.1:18000, send requests with curl, and watch what happens to a bad
request. The next lesson adds the health, readiness and metrics endpoints a
cluster needs; the Dockerfile lesson packages the result.
HTTP Bridge
If HTTP is familiar, skip ahead. Otherwise, the five facts the course uses:
- A request has a method (
GETto fetch,POSTto send data), a path (/predict), headers (content-type: application/jsonsays what the body is) and optionally a body. - A response has a status code and usually a body.
200means success;4xxcodes mean the client sent something wrong (404unknown path,422the body did not validate);5xxcodes mean the server failed (503not ready, which the next lesson uses). - JSON is the text format for the bodies: objects in braces with quoted
keys, numbers, strings,
trueandfalse. curlis the course's HTTP client:-X POSTsets the method,-Hadds a header,-dsends a body,-sSkeeps it quiet but shows errors.- A server listens on an address and port.
127.0.0.1is your computer only; the course's API listens on port 18000 on your laptop and, later, port 8000 inside a container.
The Pieces
FastAPI is a Python web framework built around type annotations: you declare what a request body looks like as a class, and the framework parses, validates and documents it. Pydantic is the library that does the validation; FastAPI uses it underneath. uvicorn is the server that actually listens on the port and hands requests to FastAPI. The pinned versions are FastAPI 0.156.8 and uvicorn 0.54.0.

Follow the arrows. curl sends the request to uvicorn; uvicorn hands it to
FastAPI; FastAPI checks the body against the Reading class. A valid body
continues to predict(), which turns it into a row in the model's feature
order, calls the pipeline that was loaded once at startup, and returns a
Prediction as JSON with status 200 (the green path). An invalid body never
reaches the model: FastAPI answers 422 with a list of what was wrong (the
dashed red path). The amber box is the only expensive object, loaded once,
not per request.
The Code
This is the complete first version of app/main.py, which the exercise
writes.
"""Inference API for the practice model: first version (lesson build-the-inference-api).
Loads the model once at startup and serves POST /predict. The next lesson adds
health, readiness, logging and metrics.
"""
import os
from contextlib import asynccontextmanager
import joblib
import numpy as np
from fastapi import FastAPI
from pydantic import BaseModel, Field
MODEL_PATH = os.environ.get("MODEL_PATH", "models/model.joblib")
state: dict = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
bundle = joblib.load(MODEL_PATH)
state.update(model=bundle["pipeline"], features=bundle["features"], version=bundle["version"])
yield
state.clear()
app = FastAPI(title="aim-api", lifespan=lifespan)
class Reading(BaseModel):
temperature_c: float = Field(..., ge=-50, le=200)
vibration_mm_s: float = Field(..., ge=0)
pressure_kpa: float = Field(..., ge=0)
runtime_hours: float = Field(..., ge=0)
load_percent: float = Field(..., ge=0, le=100)
ambient_c: float = Field(..., ge=-50, le=80)
class Prediction(BaseModel):
needs_service: bool
probability: float
model_version: str
@app.post("/predict", response_model=Prediction)
def predict(reading: Reading):
row = np.array([[getattr(reading, name) for name in state["features"]]], dtype=float)
probability = float(state["model"].predict_proba(row)[0, 1])
return Prediction(needs_service=probability >= 0.5, probability=round(probability, 4), model_version=state["version"])
Where the model path comes from
MODEL_PATH = os.environ.get("MODEL_PATH", "models/model.joblib") reads an
environment variable and falls back to the path that works when you run from
the project folder. Making it a variable costs one line now and pays off in
every later lesson: the container sets it to /models/model.joblib, a
Kubernetes ConfigMap sets it from outside the image, and the volume lesson
points it at a cache. Nothing about the code changes.
Loading once, in lifespan
lifespan is an async context manager that FastAPI runs around the whole
life of the application: the code before yield runs once before the first
request is accepted, the code after it runs once at shutdown. Loading the
model there, and keeping it in the module-level state dictionary, means the
expensive load happens once, and a request never pays for it. FastAPI's own
documentation uses exactly this pattern for machine learning models, and
marks the older @app.on_event("startup") style as deprecated.
The alternative, loading inside predict(), would reload a file on every
request. With the 1.6 KB model you might not notice; with the 33 MB one every
prediction would take a quarter of a second longer, and with a real model it
would be unusable.
The request and response models
Reading lists the six inputs with their types and bounds. Field(..., ge=0, le=100) means required (the ...), greater than or equal to 0, less than or
equal to 100. When a body arrives, FastAPI parses the JSON, converts types
where it safely can (the string "71.5" becomes 71.5), checks every bound,
and only then calls predict(). If anything fails, it answers 422 with the
exact location and reason, and your function never runs. The bounds are a
deployment decision: a model asked about a temperature of 500 degrees
returns a number anyway, so the API refuses inputs the model was never meant
to see.
Prediction is the response shape. response_model=Prediction makes FastAPI
validate what you return and document it. Callers get three fields: the
decision, the probability behind it, and which model version produced it.
That last field is what the release lessons use to tell versions apart from
outside.
The prediction itself
row = np.array([[getattr(reading, name) for name in state["features"]]])
builds a one-row matrix by reading the request's fields in the model's
feature order, taken from the bundle. The request is a named object, so
the order of keys in the JSON does not matter; the bundle's list does.
predict_proba(row)[0, 1] is the probability of class 1 (needs service) for
that one row. The threshold 0.5 turns it into the decision; it is a plain
number here, and a later lesson shows how to make such values configuration.
Exercise: Run the API Locally
Goal: write the first version of the API, serve it with uvicorn, and send valid and invalid requests.
Starting state: the project folder from the model lesson with .venv,
requirements.txt, train.py, app/__init__.py, app/batch.py and
models/model.joblib. Port 18000 is free (curl http://127.0.0.1:18000/
fails with exit code 7).
-
Write
app/main.pyby copying this block whole:cd ~/ai-deploy-practice/aim-api cat > app/main.py <<'EOF' """Inference API for the practice model: first version (lesson build-the-inference-api). Loads the model once at startup and serves POST /predict. The next lesson adds health, readiness, logging and metrics. """ import os from contextlib import asynccontextmanager import joblib import numpy as np from fastapi import FastAPI from pydantic import BaseModel, Field MODEL_PATH = os.environ.get("MODEL_PATH", "models/model.joblib") state: dict = {} @asynccontextmanager async def lifespan(app: FastAPI): bundle = joblib.load(MODEL_PATH) state.update(model=bundle["pipeline"], features=bundle["features"], version=bundle["version"]) yield state.clear() app = FastAPI(title="aim-api", lifespan=lifespan) class Reading(BaseModel): temperature_c: float = Field(..., ge=-50, le=200) vibration_mm_s: float = Field(..., ge=0) pressure_kpa: float = Field(..., ge=0) runtime_hours: float = Field(..., ge=0) load_percent: float = Field(..., ge=0, le=100) ambient_c: float = Field(..., ge=-50, le=80) class Prediction(BaseModel): needs_service: bool probability: float model_version: str @app.post("/predict", response_model=Prediction) def predict(reading: Reading): row = np.array([[getattr(reading, name) for name in state["features"]]], dtype=float) probability = float(state["model"].predict_proba(row)[0, 1]) return Prediction(needs_service=probability >= 0.5, probability=round(probability, 4), model_version=state["version"]) EOF -
Start the server:
.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 18000app.main:appmeans "the objectappin the moduleapp.main".--host 127.0.0.1listens on your computer only;--port 18000is the course's local port. Illustrative output:INFO: Started server process [48213] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://127.0.0.1:18000 (Press CTRL+C to quit)"Waiting for application startup" is the lifespan function running; the model is loaded between that line and "startup complete". Leave this terminal running and open a second one for the next steps.
-
Send a valid request:
curl -sS -X POST http://127.0.0.1:18000/predict \ -H 'content-type: application/json' \ -d '{"temperature_c":71.5,"vibration_mm_s":4.2,"pressure_kpa":310,"runtime_hours":12000,"load_percent":82,"ambient_c":24}' echoExpected:
{"needs_service":true,"probability":1.0,"model_version":"1.0.0"}. The server terminal logs the request with its status:"POST /predict HTTP/1.1" 200 OK. -
Before sending them, predict the status code of each of these three requests and what the error will say. Then run them:
curl -sS -o /dev/null -w 'HTTP %{http_code}\n' -X POST http://127.0.0.1:18000/predict \ -H 'content-type: application/json' -d '{"temperature_c":"hot"}' curl -sS -X POST http://127.0.0.1:18000/predict -H 'content-type: application/json' \ -d '{"temperature_c":500,"vibration_mm_s":4.2,"pressure_kpa":310,"runtime_hours":12000,"load_percent":82,"ambient_c":24}' echo curl -sS -o /dev/null -w 'HTTP %{http_code}\n' http://127.0.0.1:18000/predictExpected:
HTTP 422for the first (a string where a number is required, and five missing fields); for the second, a 422 body namingtemperature_cwithInput should be less than or equal to 200; andHTTP 405for the third, because/predictacceptsPOST, notGET. None of these reached the model. -
Open the automatic documentation in a browser at
http://127.0.0.1:18000/docs. FastAPI generated it from the two classes: the request schema, the bounds, the response shape. The raw description is at/openapi.json. This is the contract the API's callers will read. -
Stop the server with Ctrl+C in its terminal. The log shows
Shutting down,Waiting for application shutdown.andApplication shutdown complete.: the code afteryieldran.
Success: a valid body returns 200 with the three fields; the invalid
bodies return 422 with field errors; GET /predict returns 405; /docs
shows the schema; the server stops cleanly.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
Address already in use | Another process listens on 18000 | curl http://127.0.0.1:18000/ to see who answers; stop it if it is yours, or use --port 18001 |
ModuleNotFoundError: No module named 'app' | uvicorn started from another folder | cd ~/ai-deploy-practice/aim-api and start again |
FileNotFoundError: ... models/model.joblib at startup | The model is missing or the path is wrong | Run train.py, or set MODEL_PATH to the right file |
"detail":"Not Found" with 404 | A typo in the path | The path is /predict, case-sensitive |
HTTP 422 for a body you believe is valid | A field missing, misspelt or out of bounds | Read the loc and msg in the response body; they name the field |
The response has probability but no model_version | An older main.py or a missing version key in the bundle | Compare with the block above; rerun inspect_model.py |
curl: (52) Empty reply or connection refused right after start | The model is still loading | Wait for Application startup complete. |
Independent task: without changing the code, send a body whose keys are
in a different order, say ambient_c first. Predict whether the result
changes and why, then test it. Then change the threshold 0.5 to 0.9,
restart the server and predict what the first request from step 3 now
returns. Put the threshold back afterwards.
Cleanup: the server is stopped; keep the file. If you changed the
threshold, restore 0.5 so that later lessons match.
Check Your Understanding
- Why is the model loaded in
lifespanrather than insidepredict()? - A caller sends
{"temperature_c": 71.5, ...}with every field present butload_percent: 140. What status do they get, and what does the body tell them? - Why does the API read the request fields through
state["features"]instead of listing them in the code? - uvicorn listens on
127.0.0.1here but will listen on0.0.0.0in the container. What does each mean?
Answer and Reasoning
Independent task
Key order does not change the result: FastAPI parses the JSON into a
Reading object by name, and predict() reads the fields in the bundle's
feature order, so the row is the same. With the threshold at 0.9, the
first request returns needs_service: true still, because its probability
rounds to 1.0; a borderline reading would flip. The threshold decides the
decision, not the probability, which is why it is a candidate for
configuration rather than code.
Understanding check
- Loading is slow and the loaded object is reusable.
lifespanruns once before the first request;predict()runs on every request. Loading per request would add the whole load time to every prediction. 422. The body listsloc: ["body", "load_percent"]with a message that the input should be less than or equal to 100. The model was not called.- The bundle is the source of truth for the order the model expects. If the model is retrained with a different order, the API follows it without a code change, and the two cannot silently disagree.
127.0.0.1is the loopback address: only programs on the same host can connect.0.0.0.0means every network interface of the host. Inside a container the "host" is the container, so0.0.0.0is what makes the published port work; on your laptop127.0.0.1keeps the API private.