To manage API keys safely in Python, store them in environment variables rather than hardcoding them inside your source code.
During development, keep those keys in a
.envfile that is ignored by version control (like Git), and load them into your application usingos.environor thepython-dotenvlibrary.Immediately add
.envto your.gitignorefile so you never accidentally push secrets to GitHub or GitLab. Include a.env.examplefile with dummy values so teammates know which variables to set.Install
python-dotenv(pip install python-dotenv) to read the.envfile into your environment, then fetch the values usingos.getenv()oros.environ[].
import os
from dotenv import load_dotenv
load_dotenv() # Reads the .env file and adds values to os.environ
# Use os.environ[] if the app must crash immediately when a key is missing
api_key = os.environ["OPENAI_API_KEY"]
# Or use os.getenv() if you want a fallback or custom error check
optional_key = os.getenv("ANALYTICS_KEY", "default-value")