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].…