Hello and welcome to the first lesson of our final module, Deploying AI Models as Services.
In the last module, you mastered the engineering practices required to build a robust application that consumes AI models via external APIs. We covered everything from handling rate limits to managing costs and ensuring reliability.
Now, we're going to flip the script. Instead of being a consumer of AI services, you will become a creator. Your goal for this lesson is to build a REST API for a trained AI model using FastAPI. As a backend developer, you're already familiar with the principles of APIs. Today, we'll apply that knowledge to the specific task of serving an AI model, a fundamental skill for any AI Engineer.
Why FastAPI?
Before we dive into the code, let's briefly discuss the tool we'll be using. FastAPI is a modern, high-performance web framework for building APIs with Python. It has become incredibly popular in the machine learning community for several reasons:
- High Performance: It's built on top of Starlette (for the web parts) and Pydantic (for the data parts), making it one of the fastest Python frameworks available, on par with NodeJS and Go.
- Automatic Data Validation: Using Python type hints, FastAPI automatically validates incoming request data. This reduces bugs and improves security. For a backend developer, this means you get robust, schema-enforced endpoints with minimal effort.
- Automatic Interactive Documentation: FastAPI automatically generates interactive API documentation (using Swagger UI and ReDoc). This makes testing, debugging, and sharing your API incredibly simple.
- Asynchronous Support: It's designed from the ground up to support asynchronous code (
async/await), which is crucial for building I/O-bound applications that can handle many concurrent requests efficiently.
The Big Picture: From Model to Service
The process of deploying a model as an API generally follows a clear path. You take a trained model, wrap it in a web server application that exposes endpoints, and then prepare it for deployment.

Let's start by building our first API. We'll begin with a simple approach: creating a FastAPI service that acts as a proxy to an external model provider, like the Hugging Face Inference API.
1. Setting Up Your First AI API
This first approach is a great way to get started. It's simple, offloads the heavy computation to a managed service, and lets us focus on the API structure itself.
Building LLM Applications with Hugging Face Endpoints and FastAPI
The following article from MachineLearningMastery provides a clear, step-by-step guide to building a FastAPI application that interfaces with a Hugging Face model endpoint. We will follow this guide to create our first service.
Please read the 'Step-by-Step Example' section. Focus on the following parts: The pip install command to set up your environment. The initial app.py code, paying close attention to the PromptRequest class. This is a Pydantic model that defines the expected JSON structure of our incoming requests. The @app.post("/generate") function, which defines our API endpoint. Notice how it uses the PromptRequest model for validation and how it constructs and sends a request to the Hugging Face API.
Let's break down the key components from the article:
- Dependencies: You need
fastapifor the web framework itself,uvicornas the server that runs your application, andrequeststo make the outbound call to the Hugging Face API. - Pydantic Model: The line
class PromptRequest(BaseModel): prompt: stris crucial. This tells FastAPI that any POST request to an endpoint using this model must contain a JSON body with a key namedpromptwhose value is a string. If the request doesn't match this structure, FastAPI will automatically return a helpful422 Unprocessable Entityerror. - Path Operation: The
@app.post("/generate")is a "decorator" that tells FastAPI that the function below it,generate_text, is responsible for handlingPOSTrequests to the/generateURL path. - Running the Server: The command
uvicorn app:app --reloadstarts the development server.app:app: The firstapprefers to the Python file (app.py), and the secondapprefers to the FastAPI instance you created inside that file (app = FastAPI()).--reload: This is a development-only flag that automatically restarts the server whenever you save changes to the code.
Testing Your API
Once your server is running, you can test it in a few ways. The article shows how to use a Python requests script, which is a common way to interact with APIs programmatically.
However, one of FastAPI's best features is the automatic documentation. With your uvicorn server running, open your web browser and navigate to http://127.0.0.1:8000/docs. You should see a Swagger UI page that lists your /generate endpoint. You can expand it, click "Try it out," enter a JSON body like {"prompt": "Hello world"}, and execute the request directly from your browser.
2. Serving a Locally-Loaded Model
The proxy approach is useful, but in many cases, you'll want to host the model directly within your service. This gives you more control, can reduce latency, and avoids dependencies on external services. This pattern is central to the role of an AI Engineer.
The high-level architecture looks something like this, where the FastAPI backend directly manages the model.

Let's look at a code example for this pattern.
How to deploy machine learning models: Step-by-step guide to ML model deployment in production
The following article from Northflank provides a concise example of a FastAPI application that loads a machine learning model from the transformers library directly into memory and serves predictions.
Please review the Python code snippet under the heading '1. Prepare the inference app'. Don't worry about the Dockerfile or other deployment steps for now.
Notice the key differences in this approach:
-
Model Loading: The model and tokenizer are loaded from the
transformerslibrary outside thepredictfunction:model = AutoModelForSequenceClassification.from_pretrained("my-bert-model") tokenizer = AutoTokenizer.from_pretrained("my-bert-model") app = FastAPI()This is critical. Loading a model can take a significant amount of time and memory. By loading it at the application's startup, it's loaded only once and is ready to serve all incoming requests. If you were to load it inside the request function, you would incur that overhead on every single API call, leading to terrible performance.
-
Inference Logic: The inference logic (
tokenizer,model(**inputs),softmax) is now inside the request handler. It's running on the same server that's hosting the API. -
Request Handling: This example uses
await request.json()to get the raw JSON body. While this works, using a PydanticBaseModelas we did in the first example is generally a better practice for robustness.
Test your understanding!
Let's combine the best of both examples. How would you modify the Northflank code snippet to use a Pydantic model for request validation, just like we did in the first example? Assume the incoming JSON will look like {"text": "some input string"}.
Show answer
You would first import BaseModel from pydantic and define a request model. Then, you'd change the function signature of predict to use it.
from fastapi import FastAPI
from pydantic import BaseModel # Import BaseModel
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
# Define the request body model
class PredictRequest(BaseModel):
text: str
app = FastAPI()
model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english") # Using a real model
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english")
model.eval()
# Update the function signature
@app.post("/predict")
async def predict(request: PredictRequest):
# Access the data directly from the model object
inputs = tokenizer(request.text, return_tensors="pt", truncation=True)
with torch.no_grad():
logits = model(**inputs).logits
probs = torch.nn.functional.softmax(logits, dim=-1)
return {"confidence": probs.tolist()}
This version is more robust because FastAPI will automatically handle validation and error messaging if the request body is malformed.
Conclusion
In this lesson, you took a major step from being a consumer to a producer of AI services. You learned how to leverage your backend development skills to serve AI models through a REST API.
Key Takeaways:
- FastAPI is a modern, high-performance Python framework ideal for building AI/ML services due to its speed, data validation, and automatic documentation.
- You can serve a model in two main ways: by proxying requests to an external inference service or by loading the model locally within your application.
- Pydantic models are used to define your API's request schema, providing automatic validation and clear error messages.
- It is a critical performance best practice to load models at application startup, not within the request-response cycle.
- The
uvicornserver is used to run your FastAPI application during development.
What's Next?
You've successfully built an API for your model on your local machine. But how do you get it ready for production? The next step is to package your application and all its dependencies into a standardized, portable unit.
In the next lesson, you will learn how to containerize an AI application using Docker for portable deployment. This directly leverages your existing experience with Docker and is the next logical step in our journey toward production-ready AI services.