Learn how APIs turn analytical logic and machine-learning models into reusable services that applications, dashboards, agents and other systems can call safely.
Complete 12 of 24 practices (50%) and enter your name to unlock the Certificate of Participation.
An API is a contract that lets one system request a capability from another. Your Python function becomes useful beyond a notebook when it is exposed through a predictable interface.
The key shift is from “I can run this code” to “another system can call this capability reliably.”
def score_customer(features):
return model.predict([features])[0]
# API idea:
# POST /predict -> calls score_customer(...)The key shift is from “I can run this code” to “another system can call this capability reliably.”
HTTP gives APIs a common language. REST-style APIs organize capabilities around resources and predictable verbs such as GET, POST, PUT/PATCH and DELETE.
Choose the HTTP method that communicates intent; do not force every action through GET.
GET /models
POST /predict
GET /predictions/123
200 OK
400 Bad Request
404 Not Found
500 Server ErrorChoose the HTTP method that communicates intent; do not force every action through GET.
FastAPI is a popular Python framework for typed, documented APIs. The core pattern is simple: declare an app, define a route and return JSON-compatible data.
Start with a health endpoint before adding model logic. It gives operations a cheap way to verify the service is alive.
from fastapi import FastAPI
app = FastAPI()
@app.get("/health")
def health():
return {"status": "ok"}Start with a health endpoint before adding model logic. It gives operations a cheap way to verify the service is alive.
Production APIs should reject malformed input before it reaches your model. Typed request schemas make the contract explicit and reduce silent data-quality failures.
Validation is not cosmetic. It protects model assumptions and makes debugging dramatically easier.
from pydantic import BaseModel
class RiskRequest(BaseModel):
age: int
income: float
tenure_months: intValidation is not cosmetic. It protects model assumptions and makes debugging dramatically easier.
Model serving combines loading the trained artifact, reproducing preprocessing and exposing inference through an endpoint. The API contract should stay stable even when the model changes internally.
Return meaning, not only raw arrays. Clients should not need to understand your model internals.
import joblib
model = joblib.load("risk_model.joblib")
@app.post("/predict")
def predict(req: RiskRequest):
x = [[req.age, req.income, req.tenure_months]]
p = model.predict_proba(x)[0,1]
return {"risk_probability": round(float(p),4)}Return meaning, not only raw arrays. Clients should not need to understand your model internals.
Reliable services fail clearly. Good APIs distinguish client mistakes from server failures and emit logs/metrics that help you diagnose what happened.
A model with 95% accuracy is still a poor product if its API is unreliable or impossible to debug.
from fastapi import HTTPException
if req.income < 0:
raise HTTPException(
status_code=400,
detail="income must be non-negative"
)A model with 95% accuracy is still a poor product if its API is unreliable or impossible to debug.
An API creates a network surface. Even a small internal model service needs authentication, authorization, rate controls, secrets management and careful handling of sensitive data.
Security belongs in the design, not as a patch after deployment.
import os
API_KEY = os.environ["MODEL_API_KEY"]
# Compare caller token securely
# Never hard-code production secretsSecurity belongs in the design, not as a patch after deployment.
The final step is to treat the endpoint as a product interface: version it, test it, document it, monitor it and design for change.
The endpoint is the bridge between your model and the rest of the organization. Make that bridge boring, predictable and observable.
curl -X POST http://localhost:8000/predict \
-H "Content-Type: application/json" \
-d '{"age":42,"income":68000,"tenure_months":36}' The endpoint is the bridge between your model and the rest of the organization. Make that bridge boring, predictable and observable.
Open each item only after answering it in your own words.
To expose a capability through a stable contract that other systems can call.
To protect model assumptions, reject malformed data early and return clear errors.
Repeated loading adds latency and wastes resources; production services typically initialize shared artifacts at startup.
At minimum availability, latency, error rate, request volume and model/feature quality signals when appropriate.
A clear contract, validation, security, testing, documentation, observability and controlled change.
| Need | Recommended approach |
|---|---|
| Share a Python capability | API endpoint |
| Validate incoming structure | Typed schema / Pydantic |
| Protect access | Auth + authorization |
| Diagnose issues | Logs + metrics |
Complete at least 12 of the 24 practice cases (50%) and enter your name.