KKAIROSافتح التطبيق
Practical guideTested1 min read

Storing API keys in a Python project

Keep the key outside the source file and read it when the program starts. The environment is the simplest place, and it works the same on your laptop, a server or a CI job. This page uses a short Python snippet, not a Git command, and shows both the found and the missing case.

Published:

Advertisement

Scope: reading keys in code, with no Git history involved. Keeping the .env file itself out of Git is page 14.

Where should I store API keys in a Python project?

Read it with os.environ instead of writing it in the code.

What happens if the variable is not set?

os.environ["API_KEY"] raises KeyError, while os.environ.get returns None. Check for None and exit with a clear message.

Tested commands and output

Command: os.environ.get("API_KEY")

$ cat > app.py <<'EOF'
import os, sys
key = os.environ.get('API_KEY')
if key is None:
    sys.exit('API_KEY is not set')
print('loaded key starting with', key[:7] + '...')
EOF
$ API_KEY=sk-test-FAKE123 python3 app.py
loaded key starting with sk-test...
$ python3 app.py || echo "exit code $?"
API_KEY is not set
exit code 1

Note

Print only the first few characters of a key, never the whole value, when you log it.

Source: https://stackoverflow.com/questions/56995350/best-practices-python-where-to-store-api-keys-tokens (Stack Overflow question this page answers) Source: https://docs.python.org/3/library/os.html (Python os.environ docs)

Full kit: Secrets Safety Kit