30 Mins

2. Serving Models with FastAPI

Building a basic REST API using FastAPI

FastAPI is a modern, high-performance web framework for building APIs with Python based on standard type hints. To start, you instantiate the FastAPI class, which serves as the main interaction point for your application.

You define routes using decorators such as @app.get('/') or @app.post('/'), which map a URL path to a specific Python function. The framework automatically parses request parameters and handles JSON response serialization.

Operator Note: Always use type hints in your function parameters; FastAPI uses them to validate incoming data automatically.
Python 3
from fastapi import FastAPI

app = FastAPI()

@app.get('/')
def read_root():
    return {'message': 'VoidX Academy API is live'}

# Run with: uvicorn main:app --reload

Loading a pre-trained serialized model during FastAPI startup

Loading a machine learning model is often resource-intensive (e.g., memory usage, disk I/O). Performing this inside a request handler would cause latency spikes for every user.

The startup event handler is the best practice for loading your model into memory exactly once when the server starts. We use a global variable or an AppState object to store the loaded model, making it accessible throughout the application lifecycle.

Operator Note: Using the on_event hook ensures that your model is warm and ready before the first request is ever received.
Python 3
import joblib
from fastapi import FastAPI

app = FastAPI()
model = None

@app.on_event('startup')
def load_model():
    global model
    # Simulating loading a file: model = joblib.load('model.pkl')
    model = {'status': 'loaded', 'version': 1.0}

@app.get('/status')
def check_model():
    return {'model_state': model}

Defining a POST route to receive features and serve class predictions

In production, models need to process dynamic input. A POST request is the standard method for sending data (features) to the server. We use Pydantic models to define the expected request body schema.

When the POST request arrives, the server validates the input against the schema, passes the data into the model's predict function, and returns the result as a JSON object.

Operator Note: Pydantic models act as both documentation and strict validators, preventing malformed data from reaching your model logic.
Python 3
from pydantic import BaseModel
from fastapi import FastAPI

app = FastAPI()

class PredictRequest(BaseModel):
    features: list[float]

@app.post('/predict')
def predict(data: PredictRequest):
    # Simulate prediction logic
    prediction = sum(data.features) > 0
    return {'class': int(prediction)}

Handling JSON serialization of numpy types

Standard JSON libraries in Python do not know how to handle NumPy types like float32, int64, or ndarray. If you try to return these directly, the API will throw an error.

To resolve this, you must explicitly cast these values to Python native types (float, int, list) before returning them in the response dictionary.

Operator Note: Always check your model outputs; if you see 'TypeError: Object of type float32 is not JSON serializable', use the .item() method or explicit casting.
Python 3
import numpy as np
from fastapi import FastAPI

app = FastAPI()

@app.get('/numpy-test')
def get_numpy_val():
    np_val = np.float32(0.9576)
    # Cast to float to make it JSON serializable
    return {'confidence': float(np_val)}

Knowledge Check

Ready to test your understanding of 2. Serving Models with FastAPI?

Back