Skip to content
Advertisement

Store API key for requests

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?

Advertisement

Answer

“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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement