A practical guide to turning a scikit-learn model into a reliable web API with FastAPI: saving the model, loading it once, validating input, versioning and deployment.
A trained model sitting in a Jupyter notebook does not help your business. To be useful, it has to be reachable by your website, mobile app, ERP or CRM, usually through an HTTP API. Many teams get this step wrong: they reload the model on every request, accept unvalidated input, or overwrite the model file without any record of which version made which prediction.
This article walks through a clean, production-minded way to serve a scikit-learn model with FastAPI. The example predicts whether a customer is likely to churn, but the same structure works for lead scoring, demand forecasting or credit pre-screening.
Step 1: Train the model and save it as a pipeline
The most common source of bugs in ML APIs is a mismatch between training-time preprocessing and serving-time preprocessing. Avoid it by saving the whole scikit-learn Pipeline, including scalers and encoders, not just the estimator.
import joblib
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.read_csv("customers.csv")
X = df[["tenure_months", "monthly_spend", "plan"]]
y = df["churned"]
pre = ColumnTransformer([
("num", StandardScaler(), ["tenure_months", "monthly_spend"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
])
model = Pipeline([("pre", pre), ("clf", LogisticRegression(max_iter=1000))])
model.fit(X, y)
joblib.dump(model, "models/churn-v1.joblib")
In a real project you would split the data, evaluate on a hold-out set and record the metrics alongside the file. Note the file name includes a version. Also record the scikit-learn version used for training: joblib files are pickles, and loading them with a different scikit-learn version can produce warnings or fail. Pin the same version in your API's requirements.txt.
One security note: unpickling executes code, so only load model files you produced yourself or from a trusted, access-controlled store.
Step 2: Load the model once at startup
Loading a model from disk can take from milliseconds to several seconds. Doing it inside the request handler wastes time on every call. FastAPI's lifespan handler runs once when the application starts, which is the right place to load it.
from contextlib import asynccontextmanager
from typing import Literal
import joblib
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel, Field
MODEL_VERSION = "churn-v1"
state = {}
@asynccontextmanager
async def lifespan(app: FastAPI):
state["model"] = joblib.load(f"models/{MODEL_VERSION}.joblib")
yield
app = FastAPI(lifespan=lifespan)
class Customer(BaseModel):
tenure_months: int = Field(ge=0, le=600)
monthly_spend: float = Field(ge=0)
plan: Literal["basic", "standard", "premium"]
@app.post("/v1/predict")
def predict(c: Customer):
prob = float(state["model"].predict_proba(pd.DataFrame([c.model_dump()]))[0, 1])
return {"churn_probability": round(prob, 4), "model_version": MODEL_VERSION}
The handler is a plain def, not async def. scikit-learn prediction is CPU-bound and blocking; FastAPI runs synchronous handlers in a thread pool, so they do not block the event loop.
Step 3: Validate input properly
The Pydantic model above does a lot of work for free. A request with a negative tenure, a missing field or an unknown plan is rejected with a 422 response and a clear error message, before it ever reaches the model. This matters because scikit-learn will often happily produce a number from nonsense input, and nobody will notice.
Some further checks worth adding:
- Realistic ranges: set
geandlebounds based on the training data, so out-of-distribution values are caught early. - Batch limits: if you offer a batch endpoint that accepts a list of records, cap its length to protect the server.
- Personal data: do not accept or log fields the model does not need. Under the DPDP Act 2023, collecting less is the simplest way to stay compliant.
FastAPI also generates interactive documentation at /docs from these models, which makes it easy for your frontend or mobile developers to integrate.
Step 4: Version models and APIs
Models are retrained; APIs must stay stable for their consumers. Treat these as two separate kinds of version:
- API version (the
/v1/in the path) changes only when the request or response shape changes. - Model version (
churn-v1,churn-v2) changes whenever you retrain. Return it in every response and log it with each prediction, so you can trace any result back to the exact model file.
Store model files in a versioned location, such as object storage with a clear naming scheme, rather than overwriting a single model.joblib. Rolling back then becomes a configuration change. Add a /health endpoint that confirms the model is loaded, so load balancers and monitoring tools can check it.
Step 5: Deploy with uvicorn and gunicorn
During development, run the app with uvicorn:
uvicorn app:app --reload
In production on a Linux server, a common setup is gunicorn managing several uvicorn worker processes:
gunicorn app:app -k uvicorn.workers.UvicornWorker -w 4 -b 127.0.0.1:8000
Recent uvicorn releases can also manage multiple workers on their own with the --workers option; either approach is fine. Some practical points:
- Each worker is a separate process with its own copy of the model in memory. Four workers with a 500 MB model need roughly 2 GB just for the models. Choose the worker count based on CPU cores and available RAM.
- Put Nginx or a cloud load balancer in front to handle TLS, request size limits and rate limiting.
- Package the app in a Docker image with pinned dependency versions, so the server runs exactly what you tested.
- Log request IDs, latency, model version and prediction outputs (not raw personal data) so you can monitor drift over time.
Keeping the model healthy after launch
Real-world data changes. A churn model trained before a price change may become less accurate after it. Schedule a regular review: compare predictions against actual outcomes, watch the distribution of incoming features, and retrain when performance drops. Because your API returns the model version and you keep old files, switching to a retrained model and rolling back if needed are both low-risk operations.
How NextWebGen can help
NextWebGen builds web applications and APIs in Python and other stacks, and can take a model your team has trained and turn it into a secure, monitored service connected to your website, app or back-office systems. To discuss your use case, see our web development services and get in touch.



