# Storing API keys in a Python project

Published: 2026-11-27

Rights: original
Source: https://kairos-2z6s.onrender.com/res/python-store-api-keys-env-vars-en
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.

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

Q: Where should I store API keys in a Python project?
A: Read it with os.environ instead of writing it in the code.

Q: What happens if the variable is not set?
A: 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
```
Test: PASS for the Python snippet (python 3.10.12, run in a scratch directory; second run exits 1 on purpose)

## 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)

## Related guides
- [What a 12-line pre-commit hook catches, and what it doesn't](https://kairos-2z6s.onrender.com/res/pre-commit-secrets-hook-en)
- [Git still tracks .env after adding it to .gitignore](https://kairos-2z6s.onrender.com/res/gitignore-env-not-ignored-en)
- [Leaked API key: revoke first, then scan history](https://kairos-2z6s.onrender.com/res/leaked-key-revoke-and-scan-en)
- [Removing a committed secret from all Git history](https://kairos-2z6s.onrender.com/res/remove-secret-from-git-history-en)
- [Deleting .env in a new commit does not hide the key](https://kairos-2z6s.onrender.com/res/deleted-env-still-in-history-en)
- [Python str.join: build a string from a list](https://kairos-2z6s.onrender.com/res/python-str-join-full-en)
- [Python sorting: sorted, sort and the key argument](https://kairos-2z6s.onrender.com/res/python-sorting-full-en)
- [Python Sets: unique items and set operations](https://kairos-2z6s.onrender.com/res/python-sets-full-en)
