Mctaba Labs logo
BootcampData ScienceThe WhiteboardProjectsEventsMasterclassesWebinarsLearn
Book CallApply

500+ developers already in the community

Get answers, find accountability partners, and stay ahead

Join Discord →
Mctaba Labs logo

Educating 1 million students in tech by 2030.

Programs

  • Coding Bootcamp in Nairobi
  • Data Science to AI Engineering
  • HighSchool Graduates Launchpad
  • AI & Business Automation
  • Corporate Training
  • Kids & Teens
  • McTaba Story & Mission
  • Full-Stack Curriculum
  • Course Pricing & Plans
  • Frequently Asked Questions

Resources

  • Join Discord Community
  • Tech Events in Nairobi
  • Masterclasses
  • Free Resources
  • Learn
  • Data Science Guides
  • African Payments Reference
  • Campus
  • Africa Tech Talent Report
  • Partner With Us
  • Start a Project
  • Software & AI Studio
  • Our Work
  • Outcomes

Contact Us

  • 124 Manyani East Road, Lavington, Nairobi
  • +254727795603
  • Book a Discovery Call

Office Hours:

Mon-Fri: 9am - 2pm EAT

Sat: 10am - 12pm EAT

© 2026 Mctaba Labs - A product of Edtech Industries. All rights reserved.

Privacy PolicyTerms of ServiceRefund Policy
  1. Learn
  2. Data Science in Kenya
  3. Deploy a Machine Learning Model as an API with FastAPI
Bonaventure OgetoBy Bonaventure Ogeto|Updated November 3, 2026

Last checked 3 November 2026

Deploy a Machine Learning Model as an API with FastAPI

Train the model and save it with joblib. Write a FastAPI app that loads the file once and exposes a POST route with a validated input. Run it with uvicorn, test it with curl, then copy the app, model and a requirements file into a Docker image and start it with uvicorn.

In this article

  1. 1. Why a model needs an API
  2. 2. Step 2: serve it
  3. 3. Step 3: test with curl
  4. 4. Step 4: put it in a container

Why a model needs an API

McTaba runs coding and data bootcamps in Kenya. This guide is written to be useful whether or not you ever join one.

A model in a notebook helps nobody. The shop app, the M-Pesa callback or the WhatsApp bot cannot open your notebook. They can call a URL and read a reply. An API is that URL. This is a skills step on our data science career map.

We use a small payment risk example. The training data is made up and the rule behind it is invented, so this model is for learning only. You need pip install scikit-learn joblib fastapi uvicorn.

Step 1: train and save

import joblib
import numpy as np
from sklearn.ensemble import RandomForestClassifier

rng = np.random.default_rng(0)
amount = rng.uniform(100, 100000, 3000)
hour = rng.integers(0, 24, 3000)
risky = ((amount > 60000) & ((hour < 5) | (hour > 22))).astype(int)

model = RandomForestClassifier(n_estimators=50, random_state=0)
model.fit(np.c_[amount / 1000, hour], risky)
joblib.dump(model, "model.joblib")

Save as train.py and run it. You now have model.joblib. Note the feature order: amount in thousands, then hour. The API must send features in the same order.

FileJob
train.pyFits the model and saves it
model.joblibThe saved model
app.pyThe FastAPI app that loads and serves it
requirements.txtThe libraries, pinned to the versions you trained with
DockerfileHow to package it all

Serving models with FastAPI, Docker and MLflow is phase 6 of our Data Science to AI Engineering programme.

Step 2: serve it

import joblib
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI(title="Payment risk API")
model = joblib.load("model.joblib")


class Payment(BaseModel):
    amount_kes: float = Field(gt=0)
    hour: int = Field(ge=0, le=23)


@app.post("/predict")
def predict(p: Payment):
    prob = model.predict_proba([[p.amount_kes / 1000, p.hour]])[0][1]
    return {"risk": round(float(prob), 3), "review": bool(prob >= 0.5)}

Two things matter here. The model loads once when the app starts, not on every request. And the Payment class checks input before it reaches the model, so an hour of 30 or a negative amount gets a clear error and not a crash.

Start it with uvicorn app:app --port 8000. FastAPI also builds a test page for free at http://localhost:8000/docs.

Get weekly developer tips

Join 25,000+ developers. Practical guides, job tips, and new content — straight to your inbox.

No spam. Unsubscribe anytime.

Step 3: test with curl

curl -X POST http://localhost:8000/predict \
  -H "Content-Type: application/json" \
  -d '{"amount_kes": 85000, "hour": 2}'

For example, a large amount at 2 AM should come back with a high risk and review set to true. Try KES 500 at 2 PM and you should see a risk near zero. Then send {"amount_kes": -5, "hour": 30}: you get a 422 reply that names the two bad fields.

Write these three calls down as a test file before you change anything. A model API that quietly changes its answers is harder to fix than one that breaks loudly.

Step 4: put it in a container

Create requirements.txt from the environment you trained in: pip freeze | grep -iE "fastapi|uvicorn|scikit-learn|joblib|pydantic". A model saved with one scikit-learn version can fail or change behaviour under another, so pin the versions.

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app.py model.joblib ./
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

Build and run: docker build -t risk-api . then docker run -p 8000:8000 risk-api. The curl call from step 3 now hits the container. The FastAPI Docker documentation (checked on 3 November 2026) copies the requirements file first so Docker can reuse its cached layer, and says to use the list form of CMD so the app shuts down cleanly. We follow both.

What comes next

  • Add a /health route so a host can check the app is alive.
  • Log every request and reply, minus personal data. Models drift, and logs show it.
  • Version the model file. Name it with a date, and keep the last good one.

To train something worth serving, try mobile money fraud detection with machine learning. To refresh a model's data every day, see building a pipeline with Airflow and Docker. New to Python? Begin with Python for data science for beginners.

If you want this built for your business, as a WhatsApp reply or a payment check, see our AI agents service. To learn the whole path with mentors, read about the Data Science to AI Engineering programme: 5 months full time or 8 months part time, KES 140,000, next intake 11 January 2027.

Key Takeaways

  • ✓Train, save, serve, test, package: five small files give you a working model API.
  • ✓Load the model once at startup and validate every input.
  • ✓Pin library versions. A model file belongs to the version that made it.
  • ✓Keep your curl calls as tests before you change the model.

Frequently Asked Questions

Why FastAPI and not Flask?
FastAPI checks inputs for you with Pydantic classes and builds a test page at /docs. Flask also works. For a beginner API, FastAPI saves code.
Should I use pickle or joblib to save the model?
The scikit-learn docs suggest joblib for models with large numpy arrays. Only load model files you made yourself or trust, since loading can run code.
Do I need Docker to deploy?
Not to start. uvicorn on a server works. Docker makes the app run the same on your laptop and on the host, which saves hours of "it worked on mine".
How do I keep the model up to date?
Retrain on a schedule, save a dated model file, test the new file with your saved curl calls, then swap it in. Watch the logged replies for drift.

Learn data science on African data

KES 140,000

Data Science to AI Engineering: 5 months full time or 8 months part time, hybrid in Nairobi. Fraud, credit and M-Pesa data from Week 1, and every model deployed. Starts 11 January 2027.

See the Data Science programme

Need it live by next month? Our studio builds it

Related guides

  • AI vs Machine Learning vs Data Science: The Difference
  • Analyse Your M-Pesa Statement in Python
  • Forecast a Shop's Stock from Till Data

Keep reading

Catching Mobile Money Fraud with Machine Learning

A fraud model on the public PaySim dataset, judged in shillings lost and wasted alarms rather than a single accuracy score.

Read more

Data Engineering Basics: Build a Pipeline with Airflow and Docker

Start Airflow in Docker from the official compose file and build a three-task daily pipeline for shop sales: pull, clean, load.

Read more

Python for Data Science: Your First 30 Days

Thirty days, four weeks, one small script a week. Learn only the parts of Python that data work uses, with examples on made-up Kenyan shop data.

Read more

Kaggle for Beginners: Your First Competition

A plain walk through your first Kaggle entry: account, notebook, baseline model, submission file and the habits that make the second try better.

Read more

Explore related topics

Breaking Into Tech

Practical, no-nonsense guides for anyone looking to start or change their career in tech. From choosing your first language to acing interviews.

Tech Salary Data

Transparent salary data for tech roles in Africa and worldwide, updated regularly with real market research.

AI Skills & Tools

Practical AI knowledge for developers. Build your first agent, get good at RAG, and pick the right AI coding tools for real work.

Bonaventure Ogeto

Bonaventure Ogeto

Founder and CEO, Mctaba Labs

Software engineer for 8+ years. He runs a Nairobi studio that ships products on M-Pesa, WhatsApp and AI, and teaches what the studio ships. He holds a BSc in Mathematics and Computer Science.

More about the author