Lessons › Projects
Serve your model as a web API
A trained model saved to a file and served over HTTP with Flask, with input checks, response timing and a simple drift alarm.
Runs on your computer. Download the code and follow the steps.
Open the projectLevel: Advanced · Time: 40 min · You’ll practise: saving models, Flask APIs, input validation, drift monitoring
Steps
1. Train and save the model
train.py trains a random forest on the iris data and saves it, with its class names, to model.joblib.
"""Project 12, part 1: train a model and save it to a file.
Run: python train.py
"""
import joblib
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
iris = load_iris()
model = RandomForestClassifier(n_estimators=100, random_state=0).fit(iris.data, iris.target)
joblib.dump({"model": model, "classes": list(map(str, iris.target_names)), "features": iris.feature_names}, "model.joblib")
print("Saved model.joblib")2. Write the API
app.py loads the saved model once, then answers requests: /health to check it’s alive, /predict to classify, and /drift to compare recent inputs with the training data. Bad input gets a clear 400 error instead of a crash.
"""Project 12, part 2: serve the model as a web API with Flask.
Run: python app.py then open http://127.0.0.1:5000/health
"""
import time
import joblib
from flask import Flask, jsonify, request
bundle = joblib.load("model.joblib")
model, classes = bundle["model"], bundle["classes"]
app = Flask(__name__)
LOG = [] # a tiny in-memory prediction log for monitoring
@app.get("/health")
def health():
return jsonify(status="ok", model="iris-random-forest", predictions_served=len(LOG))
@app.post("/predict")
def predict():
body = request.get_json(silent=True) or {}
x = body.get("features")
if not isinstance(x, list) or len(x) != 4 or not all(isinstance(v, (int, float)) for v in x):
return jsonify(error="send JSON like {\"features\": [5.8, 2.7, 5.1, 1.9]}"), 400
start = time.perf_counter()
probs = model.predict_proba([x])[0]
best = int(probs.argmax())
LOG.append(x)
return jsonify(prediction=classes[best], confidence=round(float(probs[best]), 3),
latency_ms=round((time.perf_counter() - start) * 1000, 1))
@app.get("/drift")
def drift():
"""Compare the average of recent inputs with the training average."""
if len(LOG) < 5:
return jsonify(message="need at least 5 predictions first")
import numpy as np
from sklearn.datasets import load_iris
train_mean = load_iris().data.mean(axis=0)
live_mean = np.mean(LOG[-100:], axis=0)
shift = (np.abs(live_mean - train_mean) / train_mean).round(2).tolist()
return jsonify(relative_shift_per_feature=shift, alert=bool(max(shift) > 0.25))
if __name__ == "__main__":
app.run(debug=True)3. Test it without a server
test_api.py uses Flask’s built-in test client to call every endpoint, including a bad request and a burst of unusual inputs that trips the drift alarm.
"""Project 12, part 3: test the API without starting a server.
Run: python test_api.py
"""
from app import app
client = app.test_client()
print("GET /health ->", client.get("/health").get_json())
r = client.post("/predict", json={"features": [5.8, 2.7, 5.1, 1.9]})
print("POST /predict ->", r.status_code, r.get_json())
r = client.post("/predict", json={"features": "oops"})
print("POST bad input ->", r.status_code, r.get_json())
for x in [[7.9, 3.8, 6.9, 2.5]] * 6:
client.post("/predict", json={"features": x})
print("GET /drift ->", client.get("/drift").get_json())4. Run it for real
Start the server with python app.py, then in a second terminal send a request. On Windows PowerShell use curl.exe.
curl -X POST http://127.0.0.1:5000/predict -H "Content-Type: application/json" -d "{\"features\": [5.8, 2.7, 5.1, 1.9]}"Expected output
$ python train.py
Saved model.joblib
$ python test_api.py
GET /health -> {'model': 'iris-random-forest', 'predictions_served': 0, 'status': 'ok'}
POST /predict -> 200 {'confidence': 1.0, 'latency_ms': 15.4, 'prediction': 'virginica'}
POST bad input -> 400 {'error': 'send JSON like {"features": [5.8, 2.7, 5.1, 1.9]}'}
GET /drift -> {'alert': True, 'relative_shift_per_feature': [0.3, 0.19, 0.77, 1.01]}Stretch goals
- Deploy app.py to Render or Railway (free tiers) and call it from your phone.
- Log every request to a CSV and plot the inputs over time.
- Add an API key check so only your apps can call it.