Back to all articles
Cover for Improving a FastAPI ML API: Project Structure & Best Practices — Part 9

Improving a FastAPI ML API: Project Structure & Best Practices — Part 9

Sep 10, 2026
·21 min read·
fastapi
FastAPI
Python
Pydantic
Pydantic

In the previous part, we built an end-to-end machine learning prediction API using FastAPI and connected it with a Streamlit frontend.

The API worked, but as the project grows, keeping everything inside a single file can make the code harder to maintain.

A production-oriented API should have a clear structure where different responsibilities are separated.

For example:

  • Pydantic models should have their own module.
  • Configuration such as city tiers should be separated from the API logic.
  • Machine learning prediction logic should be independent from the FastAPI routes.
  • API responses should follow a defined structure.
  • The application should provide a way to check whether the API and model are running correctly.

In this part, we’ll improve our existing Insurance Premium Prediction API by applying these changes and creating a cleaner project structure.

Overview

Project Structure

Before we start modifying individual components, let’s first look at the new structure of the project:

09_Improving_the_FastAPI_API/
│
├── config/
│   └── city_tier.py
│
├── model/
│   ├── model.pkl
│   └── predict.py
│
├── schema/
│   ├── prediction_response.py
│   └── user_input.py
│
├── README.md
├── app.py
└── requirements.txt

This structure separates the project into three main areas:

  • config/ — stores configuration data such as city-tier information.
  • model/ — contains the trained model.pkl and machine learning prediction logic.
  • schema/ — contains Pydantic models for validating input and defining API responses.
  • app.py — acts as the main entry point and connects the different components together.
  • requirements.txt — contains the Python dependencies required to run the project.

Improving the Project Structure

As our FastAPI application grows, keeping the API routes, Pydantic schemas, configuration, and machine learning logic in a single file can make the project harder to maintain.

In the previous part, most of the prediction logic was handled inside app.py. In this version, we separate these responsibilities into dedicated folders and modules.

Our new project structure is:

Project Structure

The purpose of each folder is straightforward:

  • config/ — contains configuration data used by the application, such as the Tier 1 and Tier 2 city lists.
  • model/ — contains the trained model.pkl file and the prediction logic in predict.py.
  • schema/ — contains the Pydantic models used for validating user input and defining the prediction response.
  • app.py — serves as the main entry point and connects the different components together.
  • requirements.txt — contains the Python dependencies required to run the project.

For example, the project pins dependencies such as FastAPI, Pydantic, Pandas, Scikit-learn, and Uvicorn in requirements.txt.

fastapi==0.115.12
pydantic==2.11.4
pandas==2.2.3
scikit-learn==1.6.1
uvicorn==0.34.2

This gives each part of the application a clear responsibility instead of putting everything into one large file.

Why Separate the Logic?

A modular structure makes it easier to:

  • Maintain individual components.
  • Reuse logic across different parts of the application.
  • Test components independently.
  • Extend the API without making app.py unnecessarily large.
  • Understand the responsibility of each module.

For example, the prediction logic is now handled by model/predict.py, while app.py simply imports and uses the predict_output() function.

Similarly, app.py imports the input and response schemas from the schema package instead of defining them directly inside the application file.

So instead of thinking of the application as one large Python file, we can think of it as a collection of smaller components:

Configuration → Schemas → ML Logic → API Routes

This separation is the foundation for the improvements we’ll make throughout the rest of the project.


Separating the Pydantic Schema

As the project grows, the Pydantic model should not remain inside app.py.

In the new structure, we move the UserInput model into:

schema/
└── user_input.py

This keeps request validation and API route logic separate.

schema/user_input.py

from pydantic import BaseModel, Field, computed_field, field_validator
from typing import Literal, Annotated
from config.city_tier import tier_1_cities, tier_2_cities
 
 
# pydantic model to validate incoming data
class UserInput(BaseModel):
 
    age: Annotated[int, Field(..., gt=0, lt=120, description='Age of the user')]
    weight: Annotated[float, Field(..., gt=0, description='Weight of the user')]
    height: Annotated[float, Field(..., gt=0, lt=250, description='Height of the user')]
    income_lpa: Annotated[float, Field(..., gt=0, description='Annual salary of the user in lpa')]
    smoker: Annotated[bool, Field(..., description='Is user a smoker')]
    city: Annotated[str, Field(..., description='The city that the user belongs to')]
    occupation: Annotated[Literal['retired', 'freelancer', 'student', 'government_job',
       'business_owner', 'unemployed', 'private_job'], Field(..., description='Occupation of the user')]
 
    @field_validator('city')
    @classmethod
    def normalize_city(cls, v: str) -> str:
        v = v.strip().title()
        return v
 
    @computed_field
    @property
    def bmi(self) -> float:
        return self.weight/(self.height**2)
 
    @computed_field
    @property
    def lifestyle_risk(self) -> str:
        if self.smoker and self.bmi > 30:
            return "high"
        elif self.smoker or self.bmi > 27:
            return "medium"
        else:
            return "low"
 
    @computed_field
    @property
    def age_group(self) -> str:
        if self.age < 25:
            return "young"
        elif self.age < 45:
            return "adult"
        elif self.age < 60:
            return "middle_aged"
        return "senior"
 
    @computed_field
    @property
    def city_tier(self) -> int:
        if self.city in tier_1_cities:
            return 1
        elif self.city in tier_2_cities:
            return 2
        else:
            return 3

The model still contains the validation and computed fields from the previous version, but it is now placed in its own module. It also imports the city-tier configuration from config.city_tier rather than keeping those city lists inside the schema file.

Using the Schema in app.py

The main application can now simply import the model:

from schema.user_input import UserInput

Then the prediction endpoint can use it as the request-body type:

@app.post('/predict', response_model=PredictionResponse)
def predict_premium(data: UserInput):
    ...

This means app.py does not need to define the complete Pydantic model itself. It only uses the schema when handling the API request.

Why This Separation Matters

The responsibility is now clearer:

  • schema/user_input.py → Defines and validates incoming data
  • app.py → Handles API routes and application flow

This becomes especially useful when the application has multiple schemas or many API endpoints. Each component can evolve independently without turning app.py into a large collection of unrelated logic.


Moving City-Tier Configuration

In the previous version, the city-tier lists were part of the Pydantic schema logic.

As the project becomes more modular, configuration data should be separated from the models that use it.

We therefore create a dedicated configuration module:

config/
└── city_tier.py

config/city_tier.py

tier_1_cities = [
    "Mumbai",
    "Delhi",
    "Bangalore",
    "Chennai",
    "Kolkata",
    "Hyderabad",
    "Pune"
]
 
tier_2_cities = [
    "Jaipur",
    "Chandigarh",
    "Indore",
    "Lucknow",
    "Patna",
    "Ranchi",
    "Visakhapatnam",
    "Coimbatore",
    "Bhopal",
    "Nagpur",
    "Vadodara",
    "Surat",
    "Rajkot",
    "Jodhpur",
    "Raipur",
    "Amritsar",
    "Varanasi",
    "Agra",
    "Dehradun",
    "Mysore",
    "Jabalpur",
    "Guwahati",
    "Thiruvananthapuram",
    "Ludhiana",
    "Nashik",
    "Allahabad",
    "Udaipur",
    "Aurangabad",
    "Hubli",
    "Belgaum",
    "Salem",
    "Vijayawada",
    "Tiruchirappalli",
    "Bhavnagar",
    "Gwalior",
    "Dhanbad",
    "Bareilly",
    "Aligarh",
    "Gaya",
    "Kozhikode",
    "Warangal",
    "Kolhapur",
    "Bilaspur",
    "Jalandhar",
    "Noida",
    "Guntur",
    "Asansol",
    "Siliguri"
]

These lists contain the cities classified as Tier 1 and Tier 2 in the project. Cities that don’t appear in either list are treated as Tier 3 by the UserInput model.

Importing the Configuration

The Pydantic schema can now import these lists:

from config.city_tier import tier_1_cities, tier_2_cities

The city_tier computed field then uses the imported configuration:

@computed_field
@property
def city_tier(self) -> int:
    if self.city in tier_1_cities:
        return 1
    elif self.city in tier_2_cities:
        return 2
    else:
        return 3

Why Move It?

The main idea is separation of responsibilities.

The city_tier.py file is responsible only for city-tier configuration, while user_input.py is responsible for validating and processing user input.

This makes the structure easier to maintain. For example, if the city classification changes, we can update config/city_tier.py without modifying the Pydantic model itself.

The resulting relationship is:

  • config/city_tier.py → Stores city configuration
  • schema/user_input.py → Uses that configuration to calculate city_tier

This is one of the key architectural improvements in Part 9: separating configuration from application logic.


Separating ML Prediction Logic

In the previous version, the machine learning model was loaded and used directly inside app.py.

As the API grows, it is better to keep the machine learning logic separate from the API routes.

For this project, the ML-related code is moved into:

model/
├── model.pkl
└── predict.py

The model.pkl file contains the trained machine learning pipeline, while predict.py is responsible for loading the model and performing predictions.

model/predict.py

import pickle
import pandas as pd
 
# import the ml model
with open('model/model.pkl', 'rb') as f:
    model = pickle.load(f)
# MLFlow
MODEL_VERSION = '1.0.0'
# Get class labels from model
# (important for matching probabilities to class names)
class_labels = model.classes_.tolist()
 
def predict_output(user_input: dict):
    df = pd.DataFrame([user_input])
    # Predict the class
    predicted_class = model.predict(df)[0]
    # Get probabilities for all classes
    probabilities = model.predict_proba(df)[0]
    confidence = max(probabilities)
    # Create mapping: {class_name: probability}
    class_probs = dict(
        zip(
            class_labels,
            map(lambda p: round(p, 4), probabilities)
        )
    )
    return {
        "predicted_category": predicted_class,
        "confidence": round(confidence, 4),
        "class_probabilities": class_probs
    }

This module now handles the complete ML inference logic:

  1. Loads the trained model.
  2. Stores the model version.
  3. Gets the model’s class labels.
  4. Converts the input dictionary into a DataFrame.
  5. Generates the predicted class.
  6. Calculates probabilities for all classes.
  7. Extracts the highest probability as the confidence score.
  8. Returns the prediction information as a dictionary.

Using the Prediction Logic in app.py

The FastAPI application no longer needs to contain the ML implementation itself.

Instead, it imports the required objects:

from model.predict import predict_output, model, MODEL_VERSION

Then the /predict route simply calls the prediction function:

prediction = predict_output(user_input)

This creates a much cleaner separation:

  • model/predict.py → Handles ML inference
  • app.py → Handles API routes and HTTP requests

Why This Separation Matters

Now, if we change the machine learning implementation, we can modify predict.py without putting ML-specific code directly into our API routes.

Likewise, app.py remains focused on receiving requests, calling the prediction logic, and returning API responses.

The architecture is now:

Client
   ↓
FastAPI (`app.py`)
   ↓
Pydantic Schema
   ↓
Prediction Function
   ↓
ML Model (`model.pkl`)
   ↓
Prediction Result
   ↓
FastAPI Response

This is the key architectural improvement: the API layer and ML layer have separate responsibilities.


Normalizing City Input with a Field Validator

In the previous version, the city field was accepted as a string, but the API expected the city name to match the values stored in our city-tier configuration.

For example, these inputs represent the same city but have different formatting:

mumbai
 Mumbai
MUMBAI

To make the input consistent, we add a Pydantic field validator to the city field.

schema/user_input.py

@field_validator('city')
@classmethod
def normalize_city(cls, v: str) -> str:
    v = v.strip().title()
    return v

The validator performs two transformations:

  • strip() removes unnecessary whitespace from the beginning and end.
  • title() converts the city name into title case.

For example:

"  mUMBAI  "
        ↓
"mumbai"
        ↓
"Mumbai"

The normalized value can then be used by the city_tier computed field to check the city against the configured Tier 1 and Tier 2 lists.

Why Is This Useful?

Our city-tier configuration contains standardized city names such as "Mumbai", "Delhi", and "Bangalore".

Without normalization, an input such as " mumbai " would not match "Mumbai" in the list.

By normalizing the value before the city-tier calculation, the API can handle common formatting differences while keeping the configuration data consistent.

The flow becomes:

Raw City Input → Field Validator → Normalized City → City-Tier Calculation

This is a small change, but it makes the API’s input handling more consistent and reliable.


Adding the Home Endpoint

As we improve the project structure, we can also make the API’s routes more intentional.

The home endpoint provides a simple, human-readable response that confirms what the API is. In the current project, it is defined in app.py:

@app.get('/')
def home():
    return {'message':'Insurance Premium Prediction API'}

This endpoint can be accessed at:

GET /

When a client sends a GET request to /, the API returns:

{
  "message": "Insurance Premium Prediction API"
}

The purpose of this endpoint is simple: it gives users a basic entry point to the API and clearly identifies the application.

Human-Readable Route

The project comments this endpoint as human readable because its response is intended to be easily understood when someone visits the API directly:

GET /
        ↓
Insurance Premium Prediction API

This is different from the /health endpoint we'll add next, which is designed more for machine-readable health information.

The two routes therefore have different purposes:

  • GET / → Identifies the API
  • GET /health → Checks the API and model status

This keeps the home route simple while allowing the health endpoint to provide more operational information.


Adding a Health Check Endpoint

A health check endpoint provides a simple way to verify whether the API is running correctly and whether the machine learning model has been loaded.

In our project, we add a /health route alongside the home endpoint:

@app.get('/health')
def health_check():
    return {
        'status': 'OK',
        'version': MODEL_VERSION,
        'model_loaded': model is not None
    }

The endpoint can be accessed using:

GET /health

A successful response looks like:

{
  "status": "OK",
  "version": "1.0.0",
  "model_loaded": true
}

Understanding the Response

The response contains three pieces of information:

  • status — indicates that the API is running.
  • version — returns the current ML model version.
  • model_loaded — checks whether the model object has been successfully loaded.

The model version is defined separately in model/predict.py:

MODEL_VERSION = '1.0.0'

This makes the health endpoint useful for both developers and automated systems that need to check the basic state of the service.

Home vs Health Endpoint

We now have two simple routes with different purposes:

GET /
    ↓
Human-readable API information
 
GET /health
    ↓
Machine-readable API and model status

GET / tells us what the API is. GET /health tells us whether the API and model are ready.


Adding Model Versioning

As the API evolves, the machine learning model may also be updated or replaced. When that happens, knowing which model version is currently serving predictions becomes important.

In our project, we keep the model version in the ML module:

# MLFlow
MODEL_VERSION = '1.0.0'

The version is then imported into app.py along with the model and prediction function:

from model.predict import predict_output, model, MODEL_VERSION

Exposing the Model Version

The /health endpoint includes the model version in its response:

@app.get('/health')
def health_check():
    return {
        'status': 'OK',
        'version': MODEL_VERSION,
        'model_loaded': model is not None
    }

A response can therefore look like:

{
  "status": "OK",
  "version": "1.0.0",
  "model_loaded": true
}

Now, when someone checks the health endpoint, they can see not only whether the model is loaded, but also which version of the model is currently being served.

Why Model Versioning Matters

Suppose we later replace model.pkl with a newly trained model. Instead of having an API where the active model is unclear, we can update:

MODEL_VERSION = '1.1.0'

The health endpoint will then expose the new version automatically.

This becomes particularly useful when:

  • Tracking model deployments.
  • Debugging unexpected predictions.
  • Comparing behavior between model versions.
  • Knowing which model is currently serving production requests.

The important point is that model versioning is now part of the API’s operational information, while the actual prediction logic remains inside model/predict.py.

  • model/predict.py → Defines the active model version
  • app.py → Exposes that version through /health

This keeps model-related information close to the ML logic while making it visible through the API.


Handling Prediction Errors

When an API performs machine learning inference, unexpected errors can occur during the prediction process. For example, the model may fail to process the input or another runtime error may occur inside the prediction logic.

In this version of the project, the prediction call is wrapped in a try/except block inside the /predict endpoint.

@app.post('/predict', response_model=PredictionResponse)
def predict_premium(data: UserInput):
 
    user_input = {
        'bmi': data.bmi,
        'age_group': data.age_group,
        'lifestyle_risk': data.lifestyle_risk,
        'city_tier': data.city_tier,
        'income_lpa': data.income_lpa,
        'occupation': data.occupation
    }
 
    try:
        prediction = predict_output(user_input)
 
        return JSONResponse(
            status_code=200,
            content={'response': prediction}
        )
 
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=str(e)
        )

How It Works

The prediction operation is placed inside the try block:

try:
    prediction = predict_output(user_input)

If the prediction succeeds, the API returns the prediction with a 200 status code.

If an unexpected exception occurs, execution moves to the except block:

except Exception as e:
    return JSONResponse(
        status_code=500,
        content=str(e)
    )

The API then returns an HTTP 500 Internal Server Error response containing the error message.

The flow is therefore:

Request → Validation → Prediction → Success Response

Request → Validation → Prediction Error → 500 Response

Why Handle Errors?

Without explicit error handling, an unexpected exception during prediction could cause the endpoint to fail without providing a controlled API response.

Using try/except gives us a defined path for unexpected prediction failures while keeping the API available to return an HTTP response.

This improvement is part of the project’s move toward a more structured API, where prediction logic and error handling are separated from the core application structure.


Adding Confidence Scores and Class Probabilities

In the previous version, the API returned only the predicted insurance premium category.

For example:

{
  "predicted_category": "High"
}

In this version, we can provide more information about the model’s prediction by returning both a confidence score and the probability of each possible class.

The prediction logic is now handled inside model/predict.py.

Getting the Prediction

The model first generates the predicted class:

predicted_class = model.predict(df)[0]

Getting Class Probabilities

We then use predict_proba() to obtain the probability associated with each possible class:

probabilities = model.predict_proba(df)[0]
confidence = max(probabilities)

The highest probability is used as the model’s confidence score for the predicted class.

For example, if the model produces:

  • Low → 0.0100
  • Medium → 0.1500
  • High → 0.8400

then:

  • Predicted Category → High
  • Confidence → 0.8400

Mapping Probabilities to Class Names

The model’s class labels are obtained once when the model is loaded:

class_labels = model.classes_.tolist()

Then the labels are combined with their corresponding probabilities:

class_probs = dict(
    zip(
        class_labels,
        map(lambda p: round(p, 4), probabilities)
    )
)

This produces a dictionary such as:

{
  "Low": 0.01,
  "Medium": 0.15,
  "High": 0.84
}

Returning the Prediction Information

The prediction function now returns three pieces of information:

return {
    "predicted_category": predicted_class,
    "confidence": round(confidence, 4),
    "class_probabilities": class_probs
}

So instead of returning only the predicted category, the ML layer now provides a more informative result:

{
  "predicted_category": "High",
  "confidence": 0.84,
  "class_probabilities": {
    "Low": 0.01,
    "Medium": 0.15,
    "High": 0.84
  }
}

The actual values above are an example of the response structure, based on the examples defined in the project’s response schema, not a claim about a particular prediction.

This gives the API consumer more context about the prediction instead of providing only a single class label.

Prediction → Confidence → Class Probabilities

This improvement prepares the API for the next step: defining a structured response model that ensures every prediction response follows the expected format.


Creating a Response Model

So far, our API has focused on validating incoming data using the UserInput Pydantic model.

But an API also needs to define what it should return to the client.

For this, we create a separate response model:

schema/
├── user_input.py
└── prediction_response.py

This keeps the request schema and response schema separate.

schema/prediction_response.py

from pydantic import BaseModel, Field
from typing import Dict
 
 
class PredictionResponse(BaseModel):
    predicted_category: str = Field(
        ...,
        description="The predicted insurance premium category",
        example="High"
    )
 
    confidence: float = Field(
        ...,
        description="Model's confidence score for the predicted class (range: 0 to 1)",
        example=0.8432
    )
 
    class_probabilities: Dict[str, float] = Field(
        ...,
        description="Probability distribution across all possible classes",
        example={"Low": 0.01, "Medium": 0.15, "High": 0.84}
    )

The response model defines three fields:

  • predicted_category — the category predicted by the ML model.
  • confidence — the confidence score for the predicted class.
  • class_probabilities — the probability assigned to each possible category.

Using the Response Model in FastAPI

We import the response model into app.py:

from schema.prediction_response import PredictionResponse

Then we specify it using FastAPI’s response_model parameter:

@app.post('/predict', response_model=PredictionResponse)
def predict_premium(data: UserInput):
    ...

This tells FastAPI that the /predict endpoint is expected to return data matching the PredictionResponse structure.

Why Use a Response Model?

  • API Documentation: They provide a clear response structure in /docs.
  • Output Validation: They help ensure the API response follows the expected format.
  • Response Filtering: They can prevent unnecessary fields from being exposed in the API response.

This gives us a clean separation:

  • UserInput → Defines what the API accepts
  • PredictionResponse → Defines what the API returns

So the request and response now have clearly defined contracts:

Client Request
      ↓
UserInput
      ↓
FastAPI
      ↓
ML Prediction
      ↓
PredictionResponse
      ↓
Client Response

This makes the API easier to understand, document, and maintain as the application grows.


Connecting Everything in app.py

After separating the configuration, Pydantic schemas, and machine learning logic, app.py becomes much simpler.

Its main responsibility is now to connect these components and define the API routes.

Imports

We first import the components created in the previous sections:

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from schema.user_input import UserInput
from schema.prediction_response import PredictionResponse
from model.predict import predict_output, model, MODEL_VERSION

Here:

  • UserInput handles incoming request validation.
  • PredictionResponse defines the structure of the prediction response.
  • predict_output handles ML inference.
  • model allows the health endpoint to check whether the model is loaded.
  • MODEL_VERSION provides the current model version.

Creating the FastAPI Application

The application itself remains simple:

app = FastAPI()

The routes are then defined on this application.

Home Route

The home route provides a human-readable introduction to the API:

@app.get('/')
def home():
    return {'message':'Insurance Premium Prediction API'}

Health Route

The health endpoint exposes the API status, model version, and model loading status:

@app.get('/health')
def health_check():
    return {
        'status': 'OK',
        'version': MODEL_VERSION,
        'model_loaded': model is not None
    }

Prediction Route

Finally, the /predict endpoint connects the validated input with the ML prediction logic:

@app.post('/predict', response_model=PredictionResponse)
def predict_premium(data: UserInput):
 
    user_input = {
        'bmi': data.bmi,
        'age_group': data.age_group,
        'lifestyle_risk': data.lifestyle_risk,
        'city_tier': data.city_tier,
        'income_lpa': data.income_lpa,
        'occupation': data.occupation
    }
 
    try:
        prediction = predict_output(user_input)
 
        return JSONResponse(
            status_code=200,
            content={'response': prediction}
        )
 
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=str(e)
        )

Notice that app.py doesn't implement the ML prediction itself. It prepares the required values and delegates the actual inference to predict_output().

The New Architecture

The responsibilities are now clearly separated:

                    app.py
                      │
          ┌───────────┼───────────┐
          ↓           ↓           ↓
       schema/     model/       config/
          │           │           │
      Validation   Prediction   City Data
          │           │
          └──────┬────┘
                 ↓
           API Response

Or, from a request perspective:

Client → app.py → UserInput → predict_output() → ML Model → PredictionResponse → Client

This is the main goal of the refactoring: app.py acts as the API layer and coordinates the different components instead of containing all of their implementation details.


Complete Code Example

Now that we have separated the configuration, schemas, and machine learning logic, the complete project is organized across multiple files instead of a single app.py.

config/city_tier.py

tier_1_cities = ["Mumbai", "Delhi", "Bangalore", "Chennai", "Kolkata", "Hyderabad", "Pune"]
 
tier_2_cities = [
    "Jaipur", "Chandigarh", "Indore", "Lucknow", "Patna", "Ranchi", "Visakhapatnam", "Coimbatore",
    "Bhopal", "Nagpur", "Vadodara", "Surat", "Rajkot", "Jodhpur", "Raipur", "Amritsar", "Varanasi",
    "Agra", "Dehradun", "Mysore", "Jabalpur", "Guwahati", "Thiruvananthapuram", "Ludhiana", "Nashik",
    "Allahabad", "Udaipur", "Aurangabad", "Hubli", "Belgaum", "Salem", "Vijayawada", "Tiruchirappalli",
    "Bhavnagar", "Gwalior", "Dhanbad", "Bareilly", "Aligarh", "Gaya", "Kozhikode", "Warangal",
    "Kolhapur", "Bilaspur", "Jalandhar", "Noida", "Guntur", "Asansol", "Siliguri"
]

schema/user_input.py

from pydantic import BaseModel, Field, computed_field, field_validator
from typing import Literal, Annotated
from config.city_tier import tier_1_cities, tier_2_cities
 
 
# pydantic model to validate incoming data
class UserInput(BaseModel):
 
    age: Annotated[int, Field(..., gt=0, lt=120, description='Age of the user')]
    weight: Annotated[float, Field(..., gt=0, description='Weight of the user')]
    height: Annotated[float, Field(..., gt=0, lt=250, description='Height of the user')]
    income_lpa: Annotated[float, Field(..., gt=0, description='Annual salary of the user in lpa')]
    smoker: Annotated[bool, Field(..., description='Is user a smoker')]
    city: Annotated[str, Field(..., description='The city that the user belongs to')]
    occupation: Annotated[
        Literal[
            'retired',
            'freelancer',
            'student',
            'government_job',
            'business_owner',
            'unemployed',
            'private_job'
        ],
        Field(..., description='Occupation of the user')
    ]
 
    @field_validator('city')
    @classmethod
    def normalize_city(cls, v: str) -> str:
        v = v.strip().title()
        return v
 
    @computed_field
    @property
    def bmi(self) -> float:
        return self.weight/(self.height**2)
 
    @computed_field
    @property
    def lifestyle_risk(self) -> str:
        if self.smoker and self.bmi > 30:
            return "high"
        elif self.smoker or self.bmi > 27:
            return "medium"
        else:
            return "low"
 
    @computed_field
    @property
    def age_group(self) -> str:
        if self.age < 25:
            return "young"
        elif self.age < 45:
            return "adult"
        elif self.age < 60:
            return "middle_aged"
        return "senior"
 
    @computed_field
    @property
    def city_tier(self) -> int:
        if self.city in tier_1_cities:
            return 1
        elif self.city in tier_2_cities:
            return 2
        else:
            return 3

schema/prediction_response.py

from pydantic import BaseModel, Field
from typing import Dict
 
 
class PredictionResponse(BaseModel):
    predicted_category: str = Field(
        ...,
        description="The predicted insurance premium category",
        example="High"
    )
 
    confidence: float = Field(
        ...,
        description="Model's confidence score for the predicted class (range: 0 to 1)",
        example=0.8432
    )
 
    class_probabilities: Dict[str, float] = Field(
        ...,
        description="Probability distribution across all possible classes",
        example={"Low": 0.01, "Medium": 0.15, "High": 0.84}
    )

model/predict.py

import pickle
import pandas as pd
 
# import the ml model
with open('model/model.pkl', 'rb') as f:
    model = pickle.load(f)
 
# MLFlow
MODEL_VERSION = '1.0.0'
 
# Get class labels from model (important for matching probabilities to class names)
class_labels = model.classes_.tolist()
 
 
def predict_output(user_input: dict):
 
    df = pd.DataFrame([user_input])
 
    # Predict the class
    predicted_class = model.predict(df)[0]
 
    # Get probabilities for all classes
    probabilities = model.predict_proba(df)[0]
    confidence = max(probabilities)
 
    # Create mapping: {class_name: probability}
    class_probs = dict(
        zip(
            class_labels,
            map(lambda p: round(p, 4), probabilities)
        )
    )
 
    return {
        "predicted_category": predicted_class,
        "confidence": round(confidence, 4),
        "class_probabilities": class_probs
    }

app.py

from fastapi import FastAPI
from fastapi.responses import JSONResponse
from schema.user_input import UserInput
from schema.prediction_response import PredictionResponse
from model.predict import predict_output, model, MODEL_VERSION
 
app = FastAPI()
 
 
# human readable
@app.get('/')
def home():
    return {'message':'Insurance Premium Prediction API'}
 
 
# machine readable
@app.get('/health')
def health_check():
    return {
        'status': 'OK',
        'version': MODEL_VERSION,
        'model_loaded': model is not None
    }
 
 
@app.post('/predict', response_model=PredictionResponse)
def predict_premium(data: UserInput):
 
    user_input = {
        'bmi': data.bmi,
        'age_group': data.age_group,
        'lifestyle_risk': data.lifestyle_risk,
        'city_tier': data.city_tier,
        'income_lpa': data.income_lpa,
        'occupation': data.occupation
    }
 
    try:
        prediction = predict_output(user_input)
 
        return JSONResponse(
            status_code=200,
            content={'response': prediction}
        )
 
    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=str(e)
        )

Together, these files form the improved structure:

  • config/ → Configuration
  • schema/ → Request and response models
  • model/ → ML inference logic
  • app.py → API routes and application flow

This keeps the project modular while preserving the same core prediction workflow.


Output

After running the improved FastAPI application, we can verify the different routes and the prediction response.

Home Endpoint

Request:

GET /

Response:

{
  "message": "Insurance Premium Prediction API"
}

Health Check Endpoint

Request:

GET /health

Response:

{
  "status": "OK",
  "version": "1.0.0",
  "model_loaded": true
}

The health response confirms that the API is running, identifies the model version, and indicates whether the model has been loaded successfully.

Prediction Endpoint

Request:

POST /predict

The endpoint now returns a structured prediction containing:

{
  "predicted_category": "High",
  "confidence": 0.84,
  "class_probabilities": {
    "Low": 0.01,
    "Medium": 0.15,
    "High": 0.84
  }
}

The actual values above are an example of the response structure, based on the examples defined in the project’s response schema, not a claim about a particular prediction.

API Documentation

Because the prediction endpoint uses:

response_model=PredictionResponse

FastAPI can use the response model to generate a clearer schema in the interactive /docs interface and validate the expected response structure.

The improved API now provides three main routes:

  • GET / → API information
  • GET /health → API and model status
  • POST /predict → Insurance premium prediction

This gives us a more structured API with health monitoring, model version information, error handling, and a defined prediction response.


Code Execution Explanation

When the improved application runs, the responsibilities are now distributed across the project modules instead of being handled entirely inside app.py.

First, FastAPI starts through app.py and loads the required components from the schema and model packages. The ML model is loaded by model/predict.py, while the model version and class labels are also initialized there.

When a client sends a request to /predict, FastAPI validates the request using the UserInput Pydantic model. The city value is normalized, and the computed fields generate the features required by the ML model.

The API then collects those features into a dictionary and passes them to predict_output():

user_input = {
    'bmi': data.bmi,
    'age_group': data.age_group,
    'lifestyle_risk': data.lifestyle_risk,
    'city_tier': data.city_tier,
    'income_lpa': data.income_lpa,
    'occupation': data.occupation
}
 
prediction = predict_output(user_input)

Inside predict.py, the input is converted into a DataFrame, the model generates the predicted class, and the class probabilities are calculated. The highest probability becomes the confidence score, and the probabilities are mapped to their corresponding class labels.

Finally, the prediction result is returned through the FastAPI endpoint. If an unexpected error occurs during prediction, the except block returns a 500 response.

The complete execution flow is now:

Client → app.py → UserInput → Feature Generation → predict_output() → ML Model → Prediction + Probabilities → API Response

At the same time, the /health endpoint provides operational information such as the API status, model version, and model loading status.

This modular execution flow makes the API easier to maintain, test, and extend without putting all of the application logic inside a single file.


Key Takeaways

  • Modular Project Structure: Separating the application into config/, schema/, and model/ makes the FastAPI project easier to maintain and extend.
  • Separated Pydantic Schemas: Request validation is handled independently through the UserInput schema.
  • Configuration Separation: City-tier information is kept separately from the Pydantic model.
  • Separated ML Logic: Model loading, prediction, confidence calculation, and class probabilities are handled in model/predict.py.
  • Input Normalization: A field validator standardizes city names before they are used for feature calculation.
  • Health Check: The /health endpoint reports API status, model version, and whether the model is loaded.
  • Model Versioning: The active model version is explicitly defined and exposed through the API.
  • Error Handling: Prediction errors are handled with try/except and returned as a controlled 500 response.
  • Confidence & Probabilities: The API now returns the predicted category, confidence score, and probabilities for all classes.
  • Response Model: PredictionResponse defines and documents the expected structure of prediction responses.

The goal is not just to make the API work, but to structure it so that each component has a clear responsibility.


Conclusion

As an API grows, simply making it work is not enough. A good FastAPI application should also be well structured, maintainable, and predictable.

In this part, we improved our Insurance Premium Prediction API by separating configuration, Pydantic schemas, and machine learning logic into dedicated modules. We also added city input normalization, health monitoring, model versioning, error handling, confidence scores, and a structured response model.

The architecture is now:

Client → FastAPI → Pydantic Schema → ML Prediction Logic → Model → Structured Response

This modular approach makes it easier to modify individual components without making the entire application harder to manage.

Most importantly, we have moved from an API that simply serves predictions to one with a clearer architecture and better support for monitoring, validation, and maintainability.


What’s Next?

Now that we have improved our FastAPI machine learning API by introducing a modular project structure, validation, health checks, model versioning, error handling, confidence scores, and response models, the next step is to package and run the application in a consistent environment.

In the next part, we’ll introduce Docker and learn how containerization can help us build, package, and run applications with their required dependencies.

You’ll learn:

  • Introduction to Docker: What Docker is and why containers are useful for application development and deployment.
  • Why Docker?: How Docker helps provide consistency across environments, isolation between applications, and easier scalability.
  • How Docker Works: Understand the relationship between Dockerfiles, images, containers, and registries.
  • Docker Engine: Learn about the Docker Daemon, Docker CLI, and Docker REST API.
  • Docker Images: Understand what an image contains and how images are built, stored, distributed, and used to create containers.
  • Dockerfile: Learn how instructions such as FROM, WORKDIR, COPY, RUN, and CMD are used to define an application image.
  • Docker Containers: Understand how containers run applications from Docker images in isolated environments.
  • Docker Registry: Learn how Docker images can be stored, shared, and distributed using registries.
  • Docker Setup: Set up Docker and explore Docker Desktop before running containers.
  • Docker for Machine Learning: Understand how containerization can help package ML applications with their runtime environment and dependencies.

We’ll also work with a real Dockerfile and see how an application is packaged into an image and launched as a container.

Series: FastAPI for Machine Learning — Part 9 of 12

Enjoyed the read? Connect with me.

"Simplicity is the soul of efficiency."

— Austin Freeman

About

Shubham Nagar
Shubham NagarFull Stack AI Engineer

Full Stack AI Engineer with 3.5+ years of experience shipping production web and mobile apps. From Next.js frontends to LangChain and LangGraph RAG systems, I care about code quality and crafting architectures that scale.

Designed & Built by Shubham Nagar. © 2026 All rights reserved.

Built with Next.js • TypeScript • Tailwind • MDX • Vercel

Improving a FastAPI ML API: Project Structure & Best Practices — Part 9