If your API only serves other applications — cron jobs, webhooks, internal services — rather than users logging in with accounts, then JWT is a sledgehammer for a nail. The right solution is an API key sent via the X-API-Key header: use fastapi.security.APIKeyHeader together with a reusable dependency, and validate the key with secrets.compare_digest to prevent timing attacks. It takes just a few lines of code, Swagger UI picks it up automatically, and it can protect a single route, a whole router, or the entire application.
The Problem: Manual Key Checks in Every Route
A common “homemade” API key check reads the header directly in the handler:
from fastapi import FastAPI, HTTPException, Requestapp = FastAPI()API_KEY = "sk-demo-9f2c1a7b"@app.get("/orders")def list_orders(request: Request): if request.headers.get("X-API-Key") != API_KEY: raise HTTPException(401, "Sai API key") return [{"id": 1, "code": "DH-001"}]
This has 3 drawbacks: repeated code in every route, the != operator compares strings with early exit on the first differing character — an attacker can measure response times to guess each character one by one (timing attack) — and Swagger UI doesn’t know the endpoint requires authentication, so the generated docs are incomplete.
The Fix: APIKeyHeader + Reusable Dependency
FastAPI ships a security scheme for API keys. Declare it once, reuse it on every route:
import secretsfrom fastapi import Depends, FastAPI, HTTPException, Security, statusfrom fastapi.security import APIKeyHeaderAPI_KEY = "sk-demo-9f2c1a7b" # in practice, read from an environment variableapi_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)def get_api_key(api_key: str | None = Security(api_key_header)) -> str: if not api_key or not secrets.compare_digest(api_key, API_KEY): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Thieu hoac sai API key", ) return api_keyapp = FastAPI()@app.get("/orders", dependencies=[Depends(get_api_key)])def list_orders(): return [{"id": 1, "code": "DH-001"}]
The beauty of this: dependencies=[Depends(get_api_key)] protects the route with a single parameter — pass it to APIRouter or FastAPI(...) to protect a whole router instead. Setting auto_error=False lets you return your own friendly 401 message instead of FastAPI’s default 403. Most importantly, secrets.compare_digest compares in constant time, defeating timing attacks. And since this is a standard OpenAPI security scheme, Swagger UI automatically shows an Authorize button for entering the key when testing the API.
Apply It to Your Project
Never hardcode the key in source like the example above — read it from an environment variable or pydantic-settings, with a different key per dev/staging/prod environment. Rotate keys periodically (create a new key → update clients → delete the old key). And remember: the API key travels in the header as plain text, so HTTPS is mandatory — without it, the key leaks on the very first request.
Related Posts
- FastAPI: Write Custom Middleware to Measure Request Time and Log in 5 Minutes
- FastAPI: Stop API Spam with SlowAPI Rate Limiting in 5 Minutes
- FastAPI: Secure File Uploads with UploadFile — Validate File Type and Size in 5 Minutes
FAQ
How is an API key different from JWT, and when should I use each?
An API key is a fixed string that identifies the application calling the API (server-to-server); it doesn’t expire. JWT identifies a user, has a lifetime, and carries a payload. Use API keys for cron jobs, webhooks, and internal services; use JWT when users log in with accounts. This post and the blog’s JWT articles complement each other.
Where should the key be stored securely?
In an environment variable or a secret manager (Doppler, Vault…), never committed to git. With FastAPI, centralize it in pydantic-settings so it’s read and validated at app startup.
What if I want the key in a query param or a cookie?
FastAPI provides APIKeyQuery and APIKeyCookie — just swap the scheme. Headers are still recommended, because keys in URLs get written into server logs and browser history.
What if a key leaks?
Rotate in 3 steps: create a new key, update the clients, then delete the old key. If you have many clients, store the list of valid keys in a database or Redis instead of a single constant.
Why use secrets.compare_digest instead of == ?
Comparing strings with == stops at the first differing character, so response timing “leaks” how long the correct prefix is — an attacker guesses each character by measuring time. compare_digest always compares the whole string, keeping timing constant and defeating this attack.
References
- FastAPI docs — Security, first steps: https://fastapi.tiangolo.com/tutorial/security/first-steps/
- Python docs — secrets module: https://docs.python.org/3/library/secrets.html
