Get startedGet started for free

Securing APIs with key authentication

You're building a secure API and need to implement API key verification. The API will check for a key in the X-API-Key header of each request and verify it against a predefined secret. You'll use FastAPI's built-in security features to implement this authentication system.

The FastAPI and HTTPException classes have been pre-imported.

This exercise is part of the course

Deploying AI into Production with FastAPI

View Course

Exercise instructions

  • Import the necessary function to handle dependencies from FastAPI.
  • Create an API key header instance to create a dependency to validate incoming API key in the request.
  • Complete the verify_api_key function by checking the incoming api_key with the predefined secret key.
  • Raise an HTTP exception when an invalid key is passed in the request.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Import the function that handles dependencies
from fastapi import ____
from fastapi.security import APIKeyHeader

# Create the API key instance
api_key_header = ____(name="X-API-Key")
API_KEY = "your_secret_key"

# Pass the APIKeyHeader instance and verify against input api_key
def verify_api_key(api_key: str = Depends(____)):
    if api_key != ____:  
      	# Raise the HTTP exception here
        raise ____(status_code=403, detail="Invalid API Key")  
    return api_key
Edit and Run Code