Skip to main content
Every real-world application needs configuration: API keys, database URLs, secret keys, debug flags, port numbers. Hardcoding these values directly in your source code is a security risk — they may end up committed to a public Git repository, visible to every developer, or wrong for a different deployment environment. The industry-standard solution is environment variables, and the most convenient way to manage them during development is a .env file loaded with python-dotenv.

Why You Need Environment Variables

Consider a naive approach:
This approach has serious problems:
  • Secrets are embedded directly in your source code.
  • They will be committed to Git and potentially exposed publicly.
  • Every developer working on the project has to edit the source file.
  • Production, staging, and development environments all need different values.
The solution is to read these values from environment variables instead:
Your code simply asks the operating system for the value — it never hard-codes where that value comes from.

What is a .env File?

A .env file is a plain text file that stores environment variables as KEY=VALUE pairs, one per line:
Instead of typing multiple export commands in every terminal session, you write the variables once in this file.

Setting Up python-dotenv

Install the package:
Call load_dotenv() at the very beginning of your application — before you read any environment variables:
After load_dotenv() runs, every variable from .env behaves exactly like a regular OS environment variable.

Safe Variable Access

Prefer os.environ.get() over os.environ[]. The get() method returns None when a variable is missing rather than raising a KeyError. You can also supply a fallback default:

Complete Example

.env
app.py

Project Structure

Never commit .env to Git. Add it to .gitignore immediately:
A .env file typically contains API keys, database passwords, and secret tokens. Exposing them in a public repository can lead to serious security breaches and unexpected billing charges.

Sharing Projects Safely

Instead of sharing your real .env, create a template named .env.example with placeholder values:
Teammates copy it and fill in their own values:

Best Practices

Common Environment Variables

Environment variables and .env files are a standard practice across all major Python frameworks — FastAPI, Flask, Django, and beyond. The pattern is the same everywhere: store configuration outside your code, load it at startup, and access it via os.environ.get().