@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 2 |
from fastapi import HTTPException, Security, Depends from fastapi.security import APIKeyHeader |
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 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.