Milestone 4: Production Model Serving API
Exposing the Casford Pipeline via FastAPI
In this mission, you are tasked with wrapping your trained Casford classification pipeline into a production-grade REST API using FastAPI. The API must ingest raw feature vectors, pass them through the scikit-learn pipeline, and return the classification label with an associated confidence score.
Follow these strict steps: 1) Load your saved model artifact (using joblib), 2) Define a Pydantic model for request body validation to ensure incoming data matches your feature schema, 3) Initialize the FastAPI app and define an inference route that performs error handling for malformed requests.
Your endpoint must handle a POST request at '/predict' and return a JSON response containing the prediction and probability fields.
from fastapi import FastAPI, HTTPException from pydantic import BaseModel import joblib import numpy as np # Mocking a saved pipeline # In your project, replace with: pipeline = joblib.load('model.pkl') class MockPipeline: def predict(self, x): return np.array(['class_a']) def predict_proba(self, x): return np.array([[0.9, 0.1]]) app = FastAPI() pipeline = MockPipeline() class DataPayload(BaseModel): features: list[float] @app.post('/predict') def predict(payload: DataPayload): try: data = np.array(payload.features).reshape(1, -1) pred = pipeline.predict(data)[0] conf = float(pipeline.predict_proba(data).max()) return {'prediction': pred, 'probability': conf} except Exception as e: raise HTTPException(status_code=400, detail=str(e))
Containerizing for Production
Now that your API is functional, you must bridge the environment gap by creating a Dockerfile. This ensures that the dependencies, Python version, and system libraries required for your Casford pipeline are consistent across development, staging, and production environments.
Your mission is to construct a Dockerfile that starts from a lightweight 'python:3.9-slim' image, installs required packages via requirements.txt, copies your serialized model artifact into the container image, and sets the entrypoint to run the server using uvicorn.
Ensure your container exposes port 8000 and the app is set to bind to 0.0.0.0 to allow external accessibility within the Docker network.
.dockerignore to exclude your local virtual environment and unnecessary data artifacts to keep your build image size minimal.
FROM python:3.9-slim WORKDIR /app COPY requirements.txt . RUN pip install --no-cache-dir -r requirements.txt COPY . . EXPOSE 8000 CMD ['uvicorn', 'main:app', '--host', '0.0.0.0', '--port', '8000']
Objectives & Tasks
Review the tasks below and follow the interactive instructions to complete this module.
Knowledge Check
Ready to test your understanding of Milestone 4: Production Model Serving API?