Store API key for requests

Question:

I have some classes in different .py files doing REST API calls to a service using a Bearer auth key.
Since I don’t want to store the key in every class I would want to know how I should approach this.

Where and how should I store the key? How should the classes using this key access it?

Asked By: BGR

||

Answers:

One good approach would be to make a Base class which loads the api key (and potentionally any other env variables) from a .env file and stores it as a class member. Then all classes which need the api key access would just inherit from Base class.

Don’t forget to add .env file to .gitignore, so you don’t share all the private information with other users.

Answered By: Tomas_

"Best" is subjective, but frequently used on the other hand is to define your necessary keys in environment variables

For example,

config.py

import os
key = os.environ['MY_KEY']

main.py

from config import key
print(key)

Run it like

export MY_KEY='foobar'  # set instead of export on Windows
python main.py

Alternative solutions include using Hashicorp Vault, or a Key Manager
in the cloud provider of your choice.

Answered By: OneCricketeer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.