BaseModel defines typed input models for APIs. Annotated fields describe expected data types, while Pydantic parses incoming values and can convert compatible types automatically. section 9.3.2
Typed churn-model inputs
Define ModelFeatures with total_day_minutes as float and the call-count fields as integers. FastAPI can then receive this model from JSON, after which the API converts its fields into a pandas DataFrame for prediction. section 9.3.2
Listing 9.17 This code will launch an API to handle fetching predictions for the custom churn prediction model.
import sys #1
sys.path.append("../../")
from fastapi import FastAPI
from pydantic import BaseModel
import pandas as pd
import joblib
class ModelFeatures(BaseModel): #2
total_day_minutes: float
total_day_calls: int
num_customer_service_calls: int
model = joblib.load("../model_outputs/churn_model.sav") #3
app = FastAPI() #4
@app.post("/churn/") #5
async def get_churn_predictions( #6
features: ModelFeatures):
model_inputs = pd.DataFrame([features.total_day_calls, #7
features.total_day_minutes,
features.num_customer_service_calls]).transpose()
pred = model.clf.predict_proba(model_inputs)[0,1] #8
return {"prob_of_churn": pred} #9
Inspect the complete prediction API, including the BaseModel definition, FastAPI endpoint, DataFrame construction, and model invocation. section 9.3.2


