liveBook · Manning

Pydantic

As explained in Software Engineering for Data Scientists

pydantic is a Python library for parsing, validating, and converting data according to declared schemas and types.

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

How Software Engineering for Data Scientists covers it

How deep it goes
Defines a typed BaseModel schema and shows its endpoint use, but does not detail validation internals.
Examples
Uses a churn-prediction ModelFeatures schema containing minutes, calls, and customer-service-call fields.
What it assumes
Assumes basic Python and API concepts while demonstrating the schema definition needed for typed requests.
What you can do after
Apply it via FastAPI to declare and validate typed request data for a prediction service.
How it connects
Connects typed input schemas with FastAPI, Python APIs, pandas, and joblib-loaded machine-learning models.

Also explained in

Compare how 6 books explain Pydantic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Software Engineering for Data Scientists. The section links point to the parts of the book it draws on.