Environment Variables and Secrets
What You'll Learn
You'll learn how to safely store API keys using environment variables and .env files, keeping your credentials secure and out of version control.
The Problem with Hardcoded Credentials
When you started using APIs like OpenAI or Anthropic, you received an API key. The worst thing you can do is write it directly in your code:
# ❌ NEVER DO THIS
api_key = "sk-proj-abc123..." # Exposed in your code!
If you push this code to GitHub or share it, anyone can steal your key, rack up charges on your account, or access your data.
Environment Variables: The Safe Solution
Think of environment variables like a separate, private notepad that sits next to your code but never travels with it. Your code reads from this notepad at runtime.
# ✅ Safe approach
import os
api_key = os.environ["OPENAI_API_KEY"] # Read from environment
Using .env Files Locally
For development, create a .env file in your project root:
OPENAI_API_KEY=sk-proj-abc123...
ANTHROPIC_API_KEY=sk-ant-xyz789...
Load it with a library like python-dotenv:
from dotenv import load_dotenv
import os
load_dotenv() # Reads .env file
api_key = os.environ["OPENAI_API_KEY"]
The Golden Rule: Never Commit Secrets
Add .env to your .gitignore file immediately:
# .gitignore
.env
This ensures your secrets stay on your machine and never reach version control.
Key Takeaway: Store API keys in environment variables using .env files locally, always exclude them from version control, and read them with os.environ in your code—this separates credentials from code and prevents accidental exposure.