Environment Variables
AI applications commonly use API keys, passwords, database credentials, and configuration values. Environment variables allow you to keep these values outside your Python source code.
Keep secrets and configuration outside your Python code.
Instead of putting an API key directly inside a Python file, store it in an environment variable and read it when the application runs.
What Is an Environment Variable?
An environment variable is a value stored outside your Python program that your application can read while it is running.
For example:
API_KEY DATABASE_URL DEBUG APP_ENV
Your Python application can read these values when it starts.
Operating System
↓
Environment Variable
↓
Python Application
↓
Use the value
Why Should You Not Hardcode Secrets?
A beginner might write:
API_KEY = "sk-123456789" print(API_KEY)
This is a bad practice.
If the code is committed to Git or shared with another developer, the secret can be exposed.
Instead, use:
API_KEY = os.getenv("API_KEY")
Now the secret is not stored directly inside the Python source code.
Reading Environment Variables
Python provides the built-in os module for
accessing environment variables.
import os
name = os.getenv("NAME")
print(name)
If the environment variable exists, Python returns its value.
If it does not exist, os.getenv() returns
None.
Setting an Environment Variable
On Linux or macOS, you can set an environment variable from the terminal.
export API_KEY="my-secret-key"
Then Python can read it.
import os
api_key = os.getenv("API_KEY")
print(api_key)
my-secret-key
The important point is that the value does not need to exist inside the Python source code.
Providing a Default Value
os.getenv() can also provide a default
value.
import os
environment = os.getenv(
"APP_ENV",
"development"
)
print(environment)
If APP_ENV does not exist, Python uses
development.
development
This is useful for non-sensitive configuration values.
Using a .env File
For local development, a common approach is to use a
.env file.
API_KEY=my-secret-key APP_ENV=development API_URL=https://api.example.com
This gives you a convenient place to store local configuration.
But there is an important rule: do not commit your real .env file to Git.
Using python-dotenv
Python does not automatically load a
.env file into the environment.
The python-dotenv package can load those
values for local development.
Install it with:
pip install python-dotenv
Then:
from dotenv import load_dotenv
import os
load_dotenv()
api_key = os.getenv("API_KEY")
print(api_key)
load_dotenv() reads the
.env file and makes the values available
through environment variables.
Complete Example
Suppose your project looks like this:
my-ai-app/ │ ├── .env ├── .gitignore ├── main.py └── requirements.txt
Your .env file:
API_KEY=my-secret-key API_URL=https://api.example.com APP_ENV=development
Your Python file:
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("API_KEY")
api_url = os.getenv("API_URL")
environment = os.getenv("APP_ENV")
print("API URL:", api_url)
print("Environment:", environment)
API URL: https://api.example.com Environment: development
Notice that the API key is read by the application but
does not need to be written directly into
main.py.
Protect the .env File
If you use Git, add .env to your
.gitignore file.
.env __pycache__/ .venv/
This tells Git not to track the local environment file.
Project
│
├── .env
│ └── Secret values
│
├── .gitignore
│ └── Prevent .env from being committed
│
└── main.py
└── Reads environment variables
Check Required Variables
For important configuration, silently receiving
None may not be a good idea.
For example:
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("API_KEY")
if not api_key:
raise ValueError(
"API_KEY is not configured."
)
print("API key is configured.")
This makes the problem obvious when the application starts.
Environment Variables in AI Applications
AI applications frequently communicate with external services. Those services often require API keys.
For example:
.env
│
├── AI_API_KEY
├── AI_API_URL
└── MODEL_NAME
↓
Python Application
↓
AI API Client
↓
AI Service
Your application can then read the configuration.
import os
from dotenv import load_dotenv
load_dotenv()
api_key = os.getenv("AI_API_KEY")
api_url = os.getenv("AI_API_URL")
model = os.getenv("MODEL_NAME")
print("API URL:", api_url)
print("Model:", model)
Never Print Secrets
This is an important habit to develop.
Do not do this:
print(api_key)
Logs and terminal output can be saved, shared, or exposed.
Instead:
if api_key:
print("API key is configured.")
else:
print("API key is missing.")
You can confirm that a secret exists without exposing the secret itself.
Development vs Production
Environment variables are also useful when the same application runs in different environments.
Development
↓
API_URL = development API
Testing
↓
API_URL = testing API
Production
↓
API_URL = production API
The Python code can remain the same while the configuration changes.
api_url = os.getenv("API_URL")
print(api_url)
This is much cleaner than changing the source code every time you deploy the application.
Common Mistakes
Mistake 1 — Hardcoding the API key
API_KEY = "my-secret-key"
Avoid this for real secrets.
Mistake 2 — Committing .env
git add .env
Do not commit your real secret configuration file.
Mistake 3 — Assuming the variable exists
api_key = os.getenv("API_KEY")
client = APIClient(api_key)
If API_KEY is missing, the application may
fail later in a confusing place. Validate important
configuration early.
Mini Project — AI Configuration
Build a small configuration system for an AI application.
.env
AI_API_KEY=my-secret-key AI_API_URL=https://api.example.com MODEL_NAME=my-model APP_ENV=development
config.py
import os
from dotenv import load_dotenv
load_dotenv()
AI_API_KEY = os.getenv("AI_API_KEY")
AI_API_URL = os.getenv("AI_API_URL")
MODEL_NAME = os.getenv("MODEL_NAME")
APP_ENV = os.getenv(
"APP_ENV",
"development"
)
if not AI_API_KEY:
raise ValueError(
"AI_API_KEY is missing."
)
main.py
from config import (
AI_API_URL,
MODEL_NAME,
APP_ENV
)
print("API URL:", AI_API_URL)
print("Model:", MODEL_NAME)
print("Environment:", APP_ENV)
API URL: https://api.example.com Model: my-model Environment: development
This is the beginning of separating configuration from application logic.
What You Learned
- What environment variables are
- Why secrets should not be hardcoded
- Using Python's
osmodule - Using
os.getenv() - Setting environment variables
- Using a
.envfile - Using
python-dotenv - Protecting
.envwith.gitignore - Validating required configuration
- Using environment variables in AI applications
- Separating configuration from application code
Configuration belongs outside your code.
Use environment variables for API keys, credentials,
URLs, model names, and environment-specific settings.
For local development, a .env file with
python-dotenv is convenient, but never
commit real secrets to Git.