Managing Environment Variables and API Secrets Safely
Learn why you must never put API keys in your code, and how to use environment variables and .env files to keep secrets completely safe.
Every AI application you build will need secrets: API keys to access models like GPT-4, tokens to authenticate with GitHub, connection strings to reach databases, and configuration values that differ between your laptop and a production server. How you store those secrets matters enormously.Putting them directly in your code is one of the most common and costly mistakes new developers make. Anyone who reads your code — a collaborator, a potential employer browsing GitHub, or a malicious actor who finds a public repository — can see and misuse those secrets immediately.Environment variables are the standard solution. They let you keep secrets completely separate from your code, so you can safely share, publish, and collaborate on your projects without ever exposing sensitive data.
This section covers everything you need to manage secrets properly in Python:
Environment Variables
Understand what environment variables are, how Python reads them, and when to use them
Using .env Files
Use the python-dotenv library to load secrets from a .env file automatically
Almost every real-world Python project uses .env files for local development. They’re simple to set up, work on every operating system, and the python-dotenv library makes loading them a one-liner.