+91 99301 12627
MLOps & Cloud

FastAPI for Machine Learning: Serve Your Model as an API

By Mehul Prajapati

Networking equipment with cables representing serving machine learning models through a FastAPI API
On this page

Short answer: FastAPI is a modern Python web framework that’s ideal for serving machine learning models. You load the trained model once at startup, define the expected input with a Pydantic schema (so bad requests are rejected automatically), expose a /predict endpoint that returns predictions as JSON, add a /health endpoint for monitoring, and run it with Uvicorn. FastAPI also generates interactive API docs at /docs, which makes testing and sharing easy.

Key takeaways

  • Load models once, not on every request.
  • Use Pydantic to validate inputs and document the API.
  • Add /health, logging and versioning from day one.
  • Package with Docker for deployment.

Project structure

ml-service/
├── app/
│   ├── main.py
│   └── schemas.py
├── models/model.joblib
├── tests/test_api.py
└── requirements.txt

Step 1: Define input and output schemas

# app/schemas.py
from pydantic import BaseModel, Field

class CustomerFeatures(BaseModel):
    tenure_months: int = Field(ge=0)
    monthly_spend: float = Field(ge=0)
    support_tickets: int = Field(ge=0)

class Prediction(BaseModel):
    churn_probability: float
    model_version: str

Step 2: Build the API

# app/main.py
from contextlib import asynccontextmanager
from fastapi import FastAPI
import joblib, pandas as pd
from app.schemas import CustomerFeatures, Prediction

MODEL_VERSION = '1.0.0'
ml = {}

@asynccontextmanager
async def lifespan(app: FastAPI):
    ml['model'] = joblib.load('models/model.joblib')   # load once
    yield
    ml.clear()

app = FastAPI(title='Churn Prediction API', lifespan=lifespan)

@app.get('/health')
def health():
    return {'status': 'ok', 'model_version': MODEL_VERSION}

@app.post('/predict', response_model=Prediction)
def predict(features: CustomerFeatures):
    X = pd.DataFrame([features.model_dump()])
    proba = float(ml['model'].predict_proba(X)[0, 1])
    return Prediction(churn_probability=round(proba, 4), model_version=MODEL_VERSION)

Run it with uvicorn app.main:app --reload and open http://localhost:8000/docs to try the endpoint.

Step 3: Batch predictions

@app.post('/predict-batch')
def predict_batch(items: list[CustomerFeatures]):
    X = pd.DataFrame([i.model_dump() for i in items])
    probs = ml['model'].predict_proba(X)[:, 1]
    return {'churn_probabilities': [round(float(p), 4) for p in probs]}

Batching is much faster than sending one request per row.

Step 4: Test the API

# tests/test_api.py
from fastapi.testclient import TestClient
from app.main import app

def test_predict():
    with TestClient(app) as client:
        r = client.post('/predict', json={'tenure_months': 12, 'monthly_spend': 799.0, 'support_tickets': 2})
        assert r.status_code == 200
        assert 0 <= r.json()['churn_probability'] <= 1

def test_invalid_input():
    with TestClient(app) as client:
        r = client.post('/predict', json={'tenure_months': -1, 'monthly_spend': 10, 'support_tickets': 0})
        assert r.status_code == 422

Step 5: Package and deploy

Containerise the service with a Dockerfile, then deploy to a cloud container service or VM. Full walkthrough: how to deploy a machine learning model and AWS for data scientists.

Production tips

  • Same preprocessing: save a full scikit-learn Pipeline so training and serving transformations match
  • Version models and return the version in responses
  • Log inputs and predictions (without sensitive data) for monitoring and drift checks
  • Authentication: protect endpoints with API keys or OAuth
  • Workers: run multiple Uvicorn/Gunicorn workers for throughput
  • Heavy models: for large deep learning or LLM models, consider dedicated model servers or GPU instances

FastAPI vs Flask for ML

FastAPI Flask
Input validation Built-in with Pydantic Manual or via extensions
Auto API docs Yes (/docs) Via extensions
Async support Native Available, less central
Learning curve Easy with type hints Very easy

Frequently asked questions

Can FastAPI serve LLM applications?

Yes. FastAPI is widely used as the backend for chatbots and RAG apps, including streaming responses.

Is FastAPI fast enough for production?

Yes for most ML APIs; model inference time usually matters more than the framework.

Do I need to know web development?

Only basics: HTTP methods, JSON and status codes. FastAPI handles much of the rest.

Conclusion

FastAPI for machine learning gives you validated inputs, automatic docs and clean, testable endpoints with very little code. Load the model once, validate with Pydantic, test, containerise and monitor, and your model becomes a service others can use.

Learn FastAPI, Docker and deployment hands-on in our Data Science course.

Learn with Mehul Prajapati in Borivali West

At Mehul Prajapati’s institute, you get 100% practical, hands-on training by industry experts with a minimum of 5+ years of experience, plus job-oriented programmes with placement support. Weekday and weekend batches are available, with multiple 2-hour slots between 8 am and 6 pm.

Address: 12th Floor, 1214, Gold Crest Business Centre, LT Rd, Above Westside Showroom, Borivali West, Mumbai, Maharashtra 400092
Call: +91 99301 12627 / +91 96645 45072

Visit the centre or call us to choose the right course and batch and to know the current fee structure.