Get startedGet started for free

API Key Authentication

1. API Key Authentication

In this chapter, we'll learn how to secure AI models in production, focusing on API key authentication, rate limiting, and async endpoints for better performance in FastAPI.

2. Why secure APIs?

Why secure APIs? Imagine our AI model is like a precious jewel in a bank vault. Just as a bank wouldn't let anyone walk in and access their vault, we don't want unauthorized users accessing our AI endpoints. Without security we would have no accountability to prevent or audit misuse. Let's learn how to add that crucial security layer using API key authentication.

3. How API keys work

Think of API keys as special passwords that users must provide with every request. Key generation is beyond the scope of this course, but companies typically use pre-defined algorithms to generate unique API keys for each user. When a request arrives, FastAPI can check an API key in the request headers against a stored value before allowing access to our model. If the key is invalid or missing, the request is immediately rejected.

4. Understanding APIKeyHeader

FastAPI provides a specialized class to define and extract API keys in request headers called APIKeyHeader. We start by importing FastAPI's APIKeyHeader instance from fastapi.security module, which will be used to manage API key authentication as the variable header_scheme. We set 'name' to specify which header field contains our key. In this case, we will be looking for an API key named X-API-Key in the request header. 'auto_error=True' ensures FastAPI automatically handles missing keys.

5. Authenticating an endpoint

Now, let's implement our authentication logic on an endpoint. Along with our ApiKeyHeader, we need to import Depends and HTTPException from FastAPI. Depends is a special function that adds our header scheme to our endpoint definitions. We create the header scheme and set up the private secret key against which the user key will be authenticated, stored here as API_SECRET_KEY. We can now define an endpoint and use the Depends function to tell FastAPI to automatically extract the API key using the header scheme. Inside the endpoint, we compare the provided key in the request against the stored secret key. If the key doesn't match, we raise an HTTPException with a 403 Forbidden status code.

6. Authenticating an app

Let's see how to add authentication to our app. First, we define our same API key validation logic in the function verify_api_key. This is a good best practice, since this function can also be used with endpoints and other FastAPI internals. Next, we define our app with the verify_api_key function using Depends. Finally, we define /predict endpoint to accept an input parameter called text. This endpoint will return sentiment based on the input text. If authentication fails, the request never reaches our prediction code. Let's test this!

7. Testing the endpoint

To test the key authentication within the prediction endpoint, we send two requests, one with an invalid API key and another with a valid API key. On sending a request with an invalid API key, the API returns a 403 error with detail Invalid API key. On sending a request with the valid api_key, the API returns the sentiment for the input text.

8. Let's practice!

Now that we understand how to secure API calls with key-based authentication, let's practice with some exercises.