Managing Environment Variables and App Secrets in Python
Learn how to keep API keys, passwords, and configuration values out of your source code using environment variables and .env files safely.
When you start building applications that connect to APIs, databases, or external services, you’ll need a way to store sensitive values like API keys and passwords. Hardcoding them directly in your source code is one of the most common and dangerous mistakes new developers make — it means those secrets end up in your Git history, visible to anyone who can read your repository. Environment variables solve this by moving sensitive configuration out of your code entirely, into a separate layer that stays on your machine and off GitHub.
Environment variables let you keep secrets separate from your code. This section covers two approaches that work together:
Environment variables
Understand what they are and how Python reads them
Using .env files
The easy, practical way to manage secrets locally
Most Python projects use .env files — they’re simple, universally understood, and work seamlessly with Python’s python-dotenv library. That’s the approach you’ll use throughout this course.