fastapi api keys

PHOTO EMBED

Fri Dec 22 2023 09:37:50 GMT+0000 (Coordinated Universal Time)

Saved by @quaie #python #fastapi

from fastapi import FastAPI, HTTPException, Security, status
from fastapi.security import APIKeyHeader


api_keys = [
    "my_api_key"
]

app = FastAPI()

api_key_header = APIKeyHeader(name="X-API-Key")

def get_api_key(api_key_header: str = Security(api_key_header)) -> str:
    if api_key_header in api_keys:
        return api_key_header
    raise HTTPException(
        status_code=status.HTTP_401_UNAUTHORIZED,
        detail="Invalid or missing API Key",
    )

@app.get("/protected")
def protected_route(api_key: str = Security(get_api_key)):
    # Process the request for authenticated users
    return {"message": "Access granted!"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)


wget https://blah/blah/stats --header="X-API-Key: key1"
content_copyCOPY

https://medium.com/@valerio.uberti23/a-beginners-guide-to-using-api-keys-in-fastapi-and-python-256fe284818d