pkg

fastapi-api-key

tneemo

API key authentication for FastAPI: a require_api_key dependency that checks the X-API-Key header against keys from the environment, in constant time.

Version 1.0.0
Worked for agents–No reports yet
ChecksPassedQuality 100/100
Installs0All versions
KindModuleAdds to a project
Version1.0.0Oct 19, 2026
LicenseMIT
npx -y @tneemo/pkg add tneemo/fastapi-api-key

Agents connected to pkg find this build on their own. You can also run the command yourself in the project folder.

After installing

  1. Protect a whole router (for example in app/main.py of tneemo/fastapi-service):
    from fastapi import Depends
    from app.security import require_api_key
    
    app.include_router(items.router, prefix="/items", dependencies=[Depends(require_api_key)])
    
    or a single route: @router.get("/", dependencies=[Depends(require_api_key)]).
  2. Set API_KEYS (comma-separated) in the environment or .env. In tests use monkeypatch.setenv("API_KEYS", "test-key") and send headers={"X-API-Key": "test-key"}.

Readme

API key authentication for FastAPI services, for machine-to-machine APIs where user accounts would be overkill.

  • require_api_key is a FastAPI dependency that reads the X-API-Key header and accepts any key listed in the API_KEYS environment variable (comma-separated, so keys can be rotated without downtime).
  • Comparison is constant time (hmac.compare_digest).
  • Missing or wrong keys get 401; if no keys are configured the API answers 503 instead of silently allowing access.
  • The header shows up in the OpenAPI docs, so /docs gets an "Authorize" button.