Lesson 5 of 11 · 2 min
FastAPI Model Serving
from fastapi import FastAPI
from pydantic import BaseModel
import mlflow.sklearn
import numpy as np
app = FastAPI(title='Cancer Classifier API')
model = mlflow.sklearn.load_model('models:/CancerClassifier/Production')
class PredictionRequest(BaseModel):
features: list[float]
class PredictionResponse(BaseModel):
prediction: int
probability: float
label: str
@app.get('/health')
def health(): return {'status': 'ok'}
@app.post('/predict', response_model=PredictionResponse)
def predict(request: PredictionRequest):
features = np.array(request.features).reshape(1, -1)
prediction = int(model.predict(features)[0])
probability = float(model.predict_proba(features)[0][prediction])
label = 'Malignant' if prediction == 1 else 'Benign'
return PredictionResponse(prediction=prediction, probability=probability, label=label)Run: uvicorn cancer_app:app --host 0.0.0.0 --port 8000
Test: curl -X POST http://localhost:8000/predict -H 'Content-Type: application/json' -d '{"features": [17.99, 10.38, ...]}'
