Pydantic validates API inputs against declared Python types, giving FastAPI a structured way to accept model features instead of handling unstructured request data manually. section 9.3.2
Define prediction inputs
A BaseModel declares the expected churn features: total_day_minutes as a float, and total_day_calls and num_customer_service_calls as integers. FastAPI then receives these structured features in the prediction endpoint. 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 FastAPI example to see BaseModel fields connected to a loaded churn model, prediction generation, and a JSON response. section 9.3.2





