I'm working on a recommendation engine using Python and FastAPI, but I noticed that FastAPI doesn't have a built-in way to generate API keys. Up until now, I've only focused on frontend development and used cloud services for the backend, typically accessing their services through APIs. I understand that an API key is basically a random string of characters, but I'm curious about how to securely generate and store that key on the server-side. Any advice?
4 Answers
For now, you could just hardcode a simple key like `abc123` until you find a need for something more complex. It's a temporary solution that keeps you moving while you figure out your API key structure.
To generate a secure API key, create a random string with good entropy. You can also generate some random salt and store that separately. Then, hash the random string and the salt together and only share the plaintext random string with your users, leaving the rest secure. This way, even if the hashed version is compromised, the actual key remains safely hidden.
If you're planning to restrict access using an API key, ensure you have a method in place to validate that the key being used is legitimate. Think about what the purpose of the API key is—what specifics do you need to document? Why do you want an API key in the first place? Understanding your goals can really help in establishing the best approach.
Ideally, you shouldn't store the key itself in your database; instead, go with a hashed version similar to how you'd handle passwords. Of course, while developing, you might want to just hardcode a simple key in a file that you ignore in git. This way, you can keep moving forward without getting bogged down, especially through the exciting parts of your project.

Instead of implementing your own system, consider using bcrypt for hashing. You can use the same secret for all API keys, which makes it easier to look them up. Since each key will be unique, you don't necessarily need to worry about individual salts, which are more critical when multiple accounts might have the same password.