Full answer
Pattern:
python
api_key = APIKeyHeader(name="X-API-Key", auto_error=False)
def require_key(key: Annotated[str | None, Security(api_key)]):
if key is None or not secrets.compare_digest(key, EXPECTED):
raise HTTPException(status_code=401, detail="Invalid API key", headers={"WWW-Authenticate": "ApiKey"})Schemes:
APIKeyHeader,APIKeyQuery,APIKeyCookie: simple keys for service-to-service calls. Prefer headers; query keys leak into logs.HTTPBearer: returnsHTTPAuthorizationCredentialswith.schemeand.credentials(the token). Combine with JWT validation or an opaque token lookup.HTTPBasic:HTTPBasicCredentialswith.usernameand.password; the client sends them base64-encoded (not encrypted), so use only over HTTPS and compare withsecrets.compare_digestto avoid timing leaks.OAuth2PasswordBearer: for the OAuth2 password flow with a token URL (covered separately).
Behaviour details:
auto_error=True(default) makes a missing credential raise automatically. Current FastAPI answers 401 with aWWW-Authenticateheader (APIKey,BearerorBasic); older releases answered 403 for API keys and Bearer, so check your version when writing tests. Setauto_error=Falsewhen you want to handle it yourself or chain several schemes.- Using
Security()instead ofDepends()records scopes for OAuth2, and both register the scheme in OpenAPI. - Apply to a whole router with
dependencies=[Depends(require_key)]. /docsshows an Authorize dialog; the credential is stored in the browser page and sent on "Try it out".
Security basics: store only hashed API keys (like passwords), support rotation, scope keys to least privilege, rate-limit failures, and never log credentials.
python
import secrets
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Security
from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBasic, HTTPBasicCredentials, HTTPBearer
from fastapi.testclient import TestClient
app = FastAPI()
api_key = APIKeyHeader(name="X-API-Key", auto_error=False)
bearer = HTTPBearer(auto_error=False)
basic = HTTPBasic(auto_error=False)
KEY, TOKEN = "k-123", "t-456"
def key_guard(key: Annotated[str | None, Security(api_key)]):
if key is None or not secrets.compare_digest(key, KEY):
raise HTTPException(status_code=401, detail="Invalid API key")
return "service"
def bearer_guard(creds: Annotated[HTTPAuthorizationCredentials | None, Security(bearer)]):
if creds is None or not secrets.compare_digest(creds.credentials, TOKEN):
raise HTTPException(status_code=401, detail="Invalid token", headers={"WWW-Authenticate": "Bearer"})
return "token-user"
def basic_guard(creds: Annotated[HTTPBasicCredentials | None, Security(basic)]):
ok = creds is not None and secrets.compare_digest(creds.username, "teacher") and secrets.compare_digest(creds.password, "pw")
if not ok:
raise HTTPException(status_code=401, detail="Bad credentials", headers={"WWW-Authenticate": "Basic"})
return creds.username
@app.get("/key")
def by_key(who: Annotated[str, Depends(key_guard)]):
return {"who": who}
@app.get("/bearer")
def by_bearer(who: Annotated[str, Depends(bearer_guard)]):
return {"who": who}
@app.get("/basic")
def by_basic(who: Annotated[str, Depends(basic_guard)]):
return {"who": who}
c = TestClient(app)
print(c.get("/key", headers={"X-API-Key": KEY}).json(), c.get("/key").status_code)
print(c.get("/bearer", headers={"Authorization": f"Bearer {TOKEN}"}).json(), c.get("/bearer", headers={"Authorization": "Bearer bad"}).status_code)
print(c.get("/basic", auth=("teacher", "pw")).json(), c.get("/basic", auth=("teacher", "no")).headers["www-authenticate"])
print(sorted(c.get("/openapi.json").json()["components"]["securitySchemes"]))
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'who': 'service'} 401 {'who': 'token-user'} 401 {'who': 'teacher'} Basic ['APIKeyHeader', 'HTTPBasic', 'HTTPBearer']
Key points
- Security classes extract credentials; your code verifies them
- APIKeyHeader, HTTPBearer and HTTPBasic cover common schemes
- Use secrets.compare_digest for secret comparison
- They add an Authorize button to /docs via OpenAPI
- Store API keys hashed and support rotation
Common mistakes
- Comparing secrets with == instead of compare_digest
- Putting API keys in query strings
- Storing API keys in plain text
- Sending Basic credentials over plain HTTP
- Assuming the security class verifies the credential
Follow-ups
- How do you support several auth schemes on one endpoint?
- How does OAuth2PasswordBearer differ from HTTPBearer?
- How would you rotate API keys without downtime?
Tips
- Say extraction vs verification
- Mention compare_digest
- Mention OpenAPI Authorize