Environment Variables in Python
Use python-dotenv and os.environ to manage API keys and configuration securely.
Environment Variables in Python
Environment variables are key-value pairs stored in the operating system's environment — outside your code. They're the standard way to pass configuration and secrets to applications.
The .env File
For local development, create a .env file in your project root:
# .env
OPENAI_API_KEY=sk-proj-abc123...
ANTHROPIC_API_KEY=sk-ant-...
DATABASE_URL=postgresql://localhost/mydb
APP_ENV=development.env to your .gitignore immediately:
# .gitignore
.env
.env.local
.env.*.localReading Environment Variables with python-dotenv
Install the library:
pip install python-dotenvLoad variables at the start of your application:
from dotenv import load_dotenv
import os
load_dotenv() # loads .env file into environment
api_key = os.environ["OPENAI_API_KEY"] # raises KeyError if missing
api_key = os.environ.get("OPENAI_API_KEY") # returns None if missing
api_key = os.getenv("OPENAI_API_KEY", "default-value") # with fallbackUsing with the OpenAI Client
The OpenAI SDK automatically reads OPENAI_API_KEY from the environment — you don't even need to pass it explicitly:
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
# OpenAI automatically uses OPENAI_API_KEY from environment
client = OpenAI()
# Equivalent to:
# client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])Environment-Specific Configuration
Use different .env files per environment:
.env ← local development (gitignored)
.env.example ← committed to Git, shows required variables with fake values
.env.test ← test environment (gitignored)# .env.example (commit this file)
OPENAI_API_KEY=your-openai-api-key-here
DATABASE_URL=postgresql://localhost/mydb
APP_ENV=developmentNew team members copy .env.example to .env and fill in real values.
Production: Secrets Managers
In production, don't use .env files — use a proper secrets manager:
| Platform | Service |
|---------|---------|
| AWS | Secrets Manager, Parameter Store |
| GCP | Secret Manager |
| Azure | Key Vault |
| Any | HashiCorp Vault |
| Vercel/Railway | Built-in env var UI |
Secrets managers provide rotation, audit logs, and access control — .env files don't.