Hello! Welcome back to our final module, Deploying AI Models as Services.
In the last lesson, we built a high-performance streaming API for our generative AI model using FastAPI. This was a huge step forward in creating a responsive user experience. However, our API currently has a significant vulnerability: it's completely open to the public. Anyone with the URL can access it, which in a production environment could lead to unauthorized use, high operational costs, and security risks.
Today, we'll fix that. Your learning outcome is to secure an AI API endpoint using API key authentication. This is a fundamental and widely-used method for controlling access to web services. We will add a security layer to the streaming endpoint you built previously, ensuring that only authorized clients can use your AI model.
1. The "Why" and "What" of API Key Authentication
At its core, API key authentication is a simple secret token system.
- The server defines a secret string, the API Key.
- A client wanting to access a protected endpoint must include this API key in its request, typically in a custom HTTP header (like
X-API-Key). - The server checks if the provided key matches its secret key. If it does, the request is processed. If not, the server rejects the request with a
401 Unauthorizederror.
This method is very common for server-to-server communication or for granting access to third-party developers, as it's much simpler to implement than more complex protocols like OAuth2. For many AI services consumed by other backend applications, this is the perfect level of security.
A cardinal rule of software engineering is to never hardcode secrets like API keys directly in your source code. Doing so makes them visible in version control and difficult to manage. Instead, we will store our key in an environment variable, a practice you're likely familiar with from your backend development work.
2. Implementing API Key Security in FastAPI
FastAPI makes implementing this pattern straightforward using its dependency injection system. We will create a "dependency"—a function that runs before our main endpoint logic—to handle the authentication check.
Let's integrate this into the streaming application from our previous lesson.
Securing FastAPI Endpoints for MLOps: An Authentication Guide
The article 'Securing FastAPI Endpoints for MLOps' provides a clear, step-by-step guide for what we're about to do. It shows how to use FastAPI's security utilities to implement API key authentication.
Please read sections 3, 4, and 5 of the article. They cover: Setting Up the API Key and Custom Header: How to store the key and define the header. Implementing the Authentication Dependency: The core function for validating the key. Protecting the Endpoints: How to apply the dependency to your route. Focus on understanding the roles of APIKeyHeader, Security, Depends, and HTTPException.
Now, let's apply these concepts to our streaming API code.
Step 1: Storing and Loading the API Key
First, create a file named .env in your project's root directory. This file will hold our secret key.
.env
API_KEY=my-super-secret-ai-api-key
Important: Make sure to add .env to your .gitignore file to prevent committing it to version control.
Next, we'll use the python-dotenv library to load this key into our application's environment. You'll also need to import several security utilities from FastAPI.
Update the top of your main.py file:
# main.py
import os
from dotenv import load_dotenv
from fastapi import FastAPI, Depends, HTTPException, Security
from fastapi.security import APIKeyHeader
from starlette import status
# ... (rest of your imports from the previous lesson)
load_dotenv() # Load environment variables from .env file
app = FastAPI()
# Get the API key from the environment
API_KEY = os.getenv("API_KEY")
API_KEY_NAME = "X-API-Key" # The name of the header to check
# Define the API key header security scheme
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=False)
# ... (your model, tokenizer, and streamer setup from the previous lesson) ...
Step 2: Creating the Authentication Dependency
This is the function that will contain our security logic. It will extract the key from the request header and validate it.
A simple string comparison (==) is vulnerable to timing attacks, where an attacker can infer information about the secret by measuring the time it takes for the server to respond to different incorrect keys. To prevent this, we'll use Python's secrets.compare_digest function, which performs a "constant-time" comparison.
# main.py
import secrets
# ... (after api_key_header definition) ...
async def get_api_key(api_key_from_header: str = Security(api_key_header)):
"""
Dependency to validate the API key.
"""
if api_key_from_header and secrets.compare_digest(api_key_from_header, API_KEY):
return api_key_from_header
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid or missing API Key",
headers={"WWW-Authenticate": "Header"},
)
Let's break this down:
async def get_api_key(...): We define an async function that will serve as our dependency.api_key_from_header: str = Security(api_key_header): This tells FastAPI to look for the header defined inapi_key_header(X-API-Key) and pass its value to this function argument.Securityis similar toDependsbut is used for security schemes.secrets.compare_digest(): This is the crucial part. It safely compares the key from the header with our key from the.envfile.raise HTTPException(...): If the keys don't match or the header is missing, we immediately stop and send a401 Unauthorizedresponse.
Step 3: Protecting the Endpoint
The final step is to "wire" this dependency into our endpoint. We do this by adding it to the @app.get decorator.
Modify your streaming endpoint from the last lesson:
# main.py
# ... (your response_generator and other functions are unchanged) ...
@app.get(
'/query-stream/',
dependencies=[Depends(get_api_key)] # Add this line!
)
async def stream(query: str):
# This logic is now protected and will only run if get_api_key succeeds.
return StreamingResponse(response_generator(query), media_type='text/event-stream')
And that's it! Your /query-stream/ endpoint is now secured. Any request without a valid X-API-Key header will be rejected before the response_generator is even called.
3. Testing Your Secure API
Now, let's verify that our security is working correctly. We'll test three scenarios.
Securing FastAPI Endpoints for MLOps: An Authentication Guide
The 'Securing FastAPI Endpoints' article also demonstrates how to test the secured endpoint using curl. This is a standard way to interact with APIs from the command line.
Review the 'Testing the Secured Endpoints' section. Pay attention to the curl commands for testing without an API key, with an incorrect key, and with the correct key.
Test 1: Request with No API Key
curl "http://127.0.0.1:8000/query-stream/?query=hello"
You should receive a 401 Unauthorized error:
{"detail":"Invalid or missing API Key"}
Test 2: Request with an Incorrect API Key
curl -H "X-API-Key: this-is-the-wrong-key" "http://127.0.0.1:8000/query-stream/?query=hello"
You should receive the same 401 Unauthorized error.
Test 3: Request with the Correct API Key
Use the key you defined in your .env file.
curl -H "X-API-Key: my-super-secret-ai-api-key" "http://127.0.0.1:8000/query-stream/?query=hello"
Success! You should now see the streamed response from your LLM, just as you did in the previous lesson.
Testing with Swagger UI
FastAPI's automatic documentation also adapts to this security scheme. If you navigate to http://127.0.0.1:8000/docs, you will now see an "Authorize" button.

Clicking this button will open a dialog where you can enter your API key. Once authorized, you can use the "Try it out" feature to send requests to your protected endpoint directly from the browser.
Test your understanding!
Imagine you need to add a new, public endpoint /health to your API for monitoring purposes. This endpoint should simply return {"status": "ok"} and must not require an API key. How would you define this endpoint in your main.py file?
Show answer
You would define it like a normal FastAPI endpoint, but you would simply omit the dependencies=[Depends(get_api_key)] argument from the decorator.
@app.get("/health")
async def health_check():
return {"status": "ok"}
Because the get_api_key dependency isn't applied to this route, FastAPI will not perform the authentication check, leaving the endpoint public.
Conclusion
You have now implemented a crucial feature for any production-grade AI service. By adding API key authentication, you've taken control over who can access your model, laying the groundwork for secure and manageable deployments.
Key Takeaways:
- API key authentication is a simple and effective method for securing machine-to-machine APIs.
- Never hardcode secrets. Store them in environment variables and load them using a library like
python-dotenv. - FastAPI's security utilities (
APIKeyHeader,Security,Depends) make implementing authentication clean and reusable via the dependency injection pattern. - Always use a constant-time comparison function like
secrets.compare_digestwhen validating secrets to prevent timing attacks. - FastAPI's automatic docs (Swagger UI) adapt to your security schemes, making testing easy.
What's Next?
Your application is now functional, performant (thanks to streaming), and secure. The next logical step is to make it portable and easy to deploy. In our next lesson, we will containerize this application using Docker. This will leverage your existing Docker experience and prepare our AI service for deployment on any modern cloud platform.