Hard-coding API keys in source files is a security incident waiting to happen. Environment variables store configuration outside code—database URLs, model endpoints, API keys—and differ per machine (laptop vs staging vs production). The .env file plus python-dotenv is the standard local-development pattern before you adopt Docker secrets or cloud parameter stores in later volumes.
This lecture pairs directly with Calling REST APIs: load secrets first, then call external services.
Learning Objectives
By the end of this lesson, students should be able to:
- Read environment variables with
os.environandos.getenv(). - Load a
.envfile usingpython-dotenv. - Explain why secrets must not be committed to version control.
- Provide defaults and fail fast when required variables are missing.
- Separate config (env) from code (logic) following 12-factor app principles.
- Recognize production alternatives: AWS Secrets Manager, Azure Key Vault, Doppler.
Introduction: Configuration Outside Code
An environment variable is a key–value pair set in the operating system process environment. Your Python process inherits these values at startup. Deployment platforms inject different values per environment without changing source code.
# .env (never commit to git)
OPENAI_API_KEY=sk-...
DATABASE_URL=postgresql://localhost:5432/rag
MODEL_NAME=gpt-4o-mini
LOG_LEVEL=INFO
import os
from dotenv import load_dotenv
load_dotenv() # reads .env into os.environ
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
raise RuntimeError("OPENAI_API_KEY is not set")
model = os.getenv("MODEL_NAME", "gpt-4o-mini") # default if missing
Store config in the environment, not in code. Strict separation keeps the same codebase deployable to dev, staging, and production with different credentials and endpoints.
| Variable | Example Use in AI |
|---|---|
OPENAI_API_KEY | LLM provider authentication |
DATABASE_URL | Vector store / metadata DB connection |
MODEL_NAME | Switch models without code changes |
LOG_LEVEL | Control verbosity in production |
.env files are safe to share in Slack or commit privately.”
Reality: Treat every secret as compromised once exposed. Add .env to .gitignore, rotate keys immediately if leaked, and use .env.example (without real values) to document required variables.
.env.example Pattern
# .env.example (committed — documents required keys)
OPENAI_API_KEY=your-key-here
DATABASE_URL=postgresql://user:pass@host:5432/db
MODEL_NAME=gpt-4o-mini
Knowledge Check
- Short Answer: Which function loads
.envinto Python? Answer:load_dotenv()from python-dotenv. - True/False:
os.getenv("KEY", "default")returns"default"if KEY is unset. Answer: True. - Multiple Choice: Where should production secrets ultimately live? (a) GitHub repo, (b) secret manager / platform env, (c) README, (d) Jupyter output. Answer: (b).
- Short Answer: How do you read an env var without a default? Answer:
os.environ["KEY"]oros.getenv("KEY"). - True/False: Commit
.envto git so teammates share real API keys. Answer: False—gitignore.env; commit.env.examplewith placeholders. - Short Answer: What should you do if a required key is missing? Answer: Fail fast (e.g. raise
RuntimeError) rather than continue silently. - Multiple Choice: 12-factor config stores settings: (a) in source constants, (b) in the environment, (c) only in Slack, (d) inside model weights. Answer: (b).
- True/False:
MODEL_NAMEcan switch models without changing code. Answer: True. - Short Answer: Name one production secret store alternative to local
.env. Answer: AWS Secrets Manager, Azure Key Vault, or Doppler (any one). - Multiple Choice: If a secret leaks, you should: (a) ignore it, (b) rotate the key immediately, (c) print it in notebooks, (d) email it again. Answer: (b).
Key Takeaways
- Never hard-code API keys; use environment variables.
python-dotenvloads local.envfiles for development.- Commit
.env.example, gitignore.env. - Next: Type Hints for clearer, more maintainable AI codebases.
Security drill: Show a git history leak scenario. Students add .env to .gitignore and create .env.example with placeholder values.
Recap: Keep secrets in the environment, not in code; next, document intent with Type Hints.