Skip to content

Serving a Machine Learning Model With FastAPI: A Minimal Pattern

A request flowing into a model service and returning a prediction score on a gauge.

A model that only lives in a notebook helps nobody. To be used by an application, it has to be wrapped in a service that takes input, returns a prediction and keeps running. FastAPI is a popular Python framework for building exactly that kind of small API.

The minimal pattern

The core idea is simple: load the trained model once when the service starts, define what a valid request looks like, and expose one endpoint that returns a prediction.

from fastapi import FastAPI
from pydantic import BaseModel
import joblib
import pandas as pd

app = FastAPI()
model = joblib.load("model.joblib")

class Customer(BaseModel):
    tenure: int
    monthly_charges: float
    contract: str

@app.post("/predict")
def predict(customer: Customer):
    row = pd.DataFrame([customer.model_dump()])
    probability = model.predict_proba(row)[0, 1]
    return {"churn_probability": float(probability)}

This example assumes a saved scikit-learn pipeline that accepts a DataFrame with those columns. model_dump() is the Pydantic version 2 method, and older Pydantic versions use dict() instead.

Validate the input

The Customer class does real work: FastAPI uses it to check every request, rejecting a missing field or a string where a number belongs, and it generates interactive API documentation from the same definition. Bad inputs fail at the door with a clear error, instead of producing a silent wrong prediction deeper in the pipeline.

Load the model once

Loading the model inside the endpoint would reload it for every request and make the service slow. Load it at startup, as above, and reuse it. Keep training code out of the service entirely: the API should only load a model that was trained and saved elsewhere, which is where tracking runs, as in MLflow experiment tracking, pays off.

Add a health check and a version

A small endpoint that returns “ok” lets a load balancer or orchestrator know the service is running. It is also worth returning or logging the model version with each prediction, so you can tell which model produced a result when you investigate a problem.

Match the serving style to the need

An API suits predictions requested one at a time, in real time. If you only need scores for a whole table once a day, a scheduled batch job is simpler and cheaper than a live service, as laid out in batch vs real-time inference. If the model’s inputs come from many sources, a shared definition of features, as in feature stores, keeps them consistent.

Package and deploy it

Package the service and its dependencies in a container so it runs the same everywhere, as argued in why you should containerize your machine learning model. Rolling out a new model safely is its own topic, covered in blue-green vs canary deployment, and the gap between a script and a deployable product is discussed in from notebook to data product.

Monitor after launch

A running endpoint is the start, not the finish. Log the inputs and predictions, within your privacy rules, and watch for changes in both, as described in model monitoring in production and model drift.

See it in a project

My Telecom Churn Prediction project serves its model through FastAPI, with a SHAP explanation attached to each prediction.

A quick checklist

  1. Is the model loaded once at startup, not per request?
  2. Does a typed schema validate every request?
  3. Is there a health endpoint and a logged model version?
  4. Do you really need real time, or would batch scoring do?
  5. Are inputs and predictions logged so you can monitor them?

If you want a model deployed and monitored, see my machine learning and MLOps service.

FAQ

Why use FastAPI to serve a machine learning model?
It is lightweight, validates inputs with type hints, generates API documentation automatically and is simple to containerize, which suits small model-serving services.

Should I retrain the model inside the API?
No. Train and evaluate elsewhere, save the model, and have the API only load and use it, so the service stays fast and predictable.

Do I always need an API to use a model?
No. If predictions are needed in bulk on a schedule, a batch job is often simpler and cheaper than a live service.

Related posts

Leave a comment

Your email address will not be published. Required fields are marked *