1. Learn
  2. /
  3. Courses
  4. /
  5. Deploying AI into Production with FastAPI

Connected

Exercise

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.

Instructions

100 XP
  • 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.