How to define a custom security with multiple api keys in fastapi?

by dalton_moen , in category: Javascript , 2 months ago

How to define a custom security with multiple api keys in fastapi?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 2 months ago

@dalton_moen 

To define a custom security scheme with multiple API keys in FastAPI, you can create a custom dependency to handle the authentication logic. Here's an example of how you can define a custom security scheme with multiple API keys in FastAPI:

  1. Start by importing the necessary modules:
1
2
from fastapi import HTTPException, Security, Depends
from fastapi.security import APIKeyHeader


  1. Define a custom dependency to handle the authentication logic for multiple API keys. In this example, we'll create a custom dependency called api_key_dependency:
1
2
3
4
5
6
7
api_key_header = APIKeyHeader(name="API-Key")

async def api_key_dependency(api_key: str = Security(api_key_header)):
    if api_key in ["key1", "key2", "key3"]:
        return api_key
    else:
        raise HTTPException(status_code=403, detail="Invalid API key")


  1. Use the custom dependency in your FastAPI route:
1
2
3
@app.get("/items")
async def get_items(api_key: str = Depends(api_key_dependency)):
    return {"message": "Authorized API key"}


In this example, the custom dependency api_key_dependency checks if the API key provided in the request headers is valid. If the API key is valid, the route is executed successfully, otherwise, an HTTP 403 Forbidden error is raised.


By defining a custom security scheme with multiple API keys in FastAPI, you can easily create authentication logic to protect your routes and ensure that only users with valid API keys can access your API endpoints.