Deploying AI Models with Docker and Kubernetes / Serve a Model as an API

Build the inference API

Lesson 4 of 29. Open to read. No account needed.

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 (GET to fetch, POST to send data), a path (/predict), headers (content-type: application/json says what the body is) and optionally a body.
  • A response has a status code and usually a body. 200 means success; 4xx codes mean the client sent something wrong (404 unknown path, 422 the body did not validate); 5xx codes mean the server failed (503 not ready, which the next lesson uses).
  • JSON is the text format for the bodies: objects in braces with quoted keys, numbers, strings, true and false.
  • curl is the course's HTTP client: -X POST sets the method, -H adds a header, -d sends a body, -sS keeps it quiet but shows errors.
  • A server listens on an address and port. 127.0.0.1 is 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.

One request through the API: curl sends POST /predict with a JSON body to uvicorn on 127.0.0.1:18000, which hands it to FastAPI. FastAPI validates the body against the Reading model. A valid body reaches the predict function, which builds a row in the model's feature order and calls predict_proba on the pipeline loaded once at startup, returning 200 with needs_service, probability and model_version. An invalid body takes a dashed branch back to curl with 422 and field errors; the model is never called.

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).

  1. Write app/main.py by 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
    
  2. Start the server:

    .venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 18000
    

    app.main:app means "the object app in the module app.main". --host 127.0.0.1 listens on your computer only; --port 18000 is 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.

  3. 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}'
    echo
    

    Expected: {"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.

  4. 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/predict
    

    Expected: HTTP 422 for the first (a string where a number is required, and five missing fields); for the second, a 422 body naming temperature_c with Input should be less than or equal to 200; and HTTP 405 for the third, because /predict accepts POST, not GET. None of these reached the model.

  5. 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.

  6. Stop the server with Ctrl+C in its terminal. The log shows Shutting down, Waiting for application shutdown. and Application shutdown complete.: the code after yield ran.

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 seeLikely causeNext step
Address already in useAnother process listens on 18000curl 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 foldercd ~/ai-deploy-practice/aim-api and start again
FileNotFoundError: ... models/model.joblib at startupThe model is missing or the path is wrongRun train.py, or set MODEL_PATH to the right file
"detail":"Not Found" with 404A typo in the pathThe path is /predict, case-sensitive
HTTP 422 for a body you believe is validA field missing, misspelt or out of boundsRead the loc and msg in the response body; they name the field
The response has probability but no model_versionAn older main.py or a missing version key in the bundleCompare with the block above; rerun inspect_model.py
curl: (52) Empty reply or connection refused right after startThe model is still loadingWait 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

  1. Why is the model loaded in lifespan rather than inside predict()?
  2. A caller sends {"temperature_c": 71.5, ...} with every field present but load_percent: 140. What status do they get, and what does the body tell them?
  3. Why does the API read the request fields through state["features"] instead of listing them in the code?
  4. uvicorn listens on 127.0.0.1 here but will listen on 0.0.0.0 in 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

  1. Loading is slow and the loaded object is reusable. lifespan runs once before the first request; predict() runs on every request. Loading per request would add the whole load time to every prediction.
  2. 422. The body lists loc: ["body", "load_percent"] with a message that the input should be less than or equal to 100. The model was not called.
  3. 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.
  4. 127.0.0.1 is the loopback address: only programs on the same host can connect. 0.0.0.0 means every network interface of the host. Inside a container the "host" is the container, so 0.0.0.0 is what makes the published port work; on your laptop 127.0.0.1 keeps the API private.

References

24 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy