How to store API keys safely in FastAPI (and why bcrypt is the wrong tool)
This article was created with the help of AI. The code was run and checked before publishing (FastAPI 0.165.0, SQLAlchemy 2.1.9). You want scripts and bots to call your FastAPI app with an X-API-Key header. Two question
This article was created with the help of AI. The code was run and checked before publishing (FastAPI 0.165.0, SQLAlchemy 2.1.9).
You want scripts and bots to call your FastAPI app with an X-API-Key header. Two questions come up quickly: how do I store the key, and should I hash it with bcrypt like a password?
Short answer: generate a long random key, store only its SHA-256 hash, and look the key up by that hash.
Why not bcrypt?
Slow, salted hashes protect secrets that people choose, because people choose guessable ones. The Python docs say passwords "should be salted and hashed using a cryptographically strong one-way (irreversible) hash function" [1].
A generated key is different. The same docs say 32 bytes (256 bits) of randomness is believed to be sufficient for typical uses [1]. Guessing a value like that is not practical, so slowing each guess down buys you very little.
A salted slow hash also has two practical costs for keys:
- You cannot look a key up by its hash, because each row has a different salt. You need a separate key ID.
- You pay the hashing cost on every request, not just at login.
This only holds if your server generates the key. If users can type their own, treat it as a password.
A minimal version
import hashlib
import secrets
from fastapi import Depends, FastAPI, HTTPException
from fastapi.security import APIKeyHeader
from sqlalchemy import String, create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
engine = create_engine(
"sqlite:///./keys.db", connect_args={"check_same_thread": False}
)
class Base(DeclarativeBase):
pass
class ApiKey(Base):
__tablename__ = "api_keys"
id: Mapped[int] = mapped_column(primary_key=True)
owner: Mapped[str] = mapped_column(String(100))
prefix: Mapped[str] = mapped_column(String(12))
key_hash: Mapped[str] = mapped_column(String(64), unique=True, index=True)
Base.metadata.create_all(engine)
app = FastAPI()
header = APIKeyHeader(name="X-API-Key")
def get_db():
with Session(engine) as db:
yield db
def hash_key(plain: str) -> str:
return hashlib.sha256(plain.encode()).hexdigest()
def create_key(db: Session, owner: str) -> str:
plain = "demo_" + secrets.token_urlsafe(32)
db.add(ApiKey(owner=owner, prefix=plain[:10], key_hash=hash_key(plain)))
db.commit()
return plain # show once, never store
def require_key(
plain: str = Depends(header), db: Session = Depends(get_db)
) -> ApiKey:
row = db.scalar(select(ApiKey).where(ApiKey.key_hash == hash_key(plain)))
if row is None:
raise HTTPException(
401, "Invalid API key", headers={"WWW-Authenticate": "APIKey"}
)
return row
@app.get("/me")
def me(key: ApiKey = Depends(require_key)):
return {"owner": key.owner}
Save it as main.py and create a key from a Python shell:
from sqlalchemy.orm import Session
from main import create_key, engine
with Session(engine) as db:
print(create_key(db, "my-script"))
Then call /me with that value in the X-API-Key header.
Four details that matter
- Show the key once. Only the hash is saved, so you cannot show it again. Keep a short prefix so users can tell their keys apart.
-
Pass the byte count yourself.
token_urlsafe()without an argument uses a default that the docs say may change at any time [1]. -
Check which status code you get. When the header is missing, the current
APIKeyHeaderreturns 401 withWWW-Authenticate: APIKey[2]. Before FastAPI 0.122.0, the built-in security tools returned 403 [3], so older tests may expect that. - Make revoking simple. Deleting the row is enough, because the next lookup finds nothing. Check that the row belongs to the caller first, and return 404 if it does not.
Hashing does not help if a key leaks from a client or a log file. Use HTTPS, and keep the header out of your logs.
Sources (opened 2026-12-02)
- Python
secrets: https://docs.python.org/3/library/secrets.html - FastAPI security reference: https://fastapi.tiangolo.com/reference/security/
- FastAPI 403/401 change: https://fastapi.tiangolo.com/how-to/authentication-error-status-code/
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.