I'm working on a FastAPI project where I use python-dotenv to load environment variables from a .env file. Most variables load correctly, but the API_KEY variable is not being picked up by my app, even though it is present in the .env file. Other variables from the same file load as expected.
What I have:
- .env file (in the same directory as my server.py):
OPENAI_API_KEY=sk-xxxx
GOOGLE_API_KEY=AIzaSyxxxx
API_KEY=your-secure-api-key-here
PORT=8000
- Code to load and print env variables:
from dotenv import load_dotenv
from pathlib import Path
import os
env_path = Path(__file__).parent / ".env"
load_dotenv(dotenv_path=env_path)
print("Loaded environment variables from .env:")
if env_path.exists():
with open(env_path) as f:
for line in f:
line = line.strip()
if line and not line.startswith("#") and "=" in line:
key = line.split("=", 1)[0]
print(f" {key} = {os.getenv(key)}")
else:
print(f".env file not found at {env_path}")
- When I run the app, all variables print correctly except API_KEY, which is
jsdnfasdfiejaklmcasljrlkjjh323jcksdfjk.
What I’ve tried:
- Verified .env is in the correct directory.
- Restarted the server after editing .env.
- Ran echo $API_KEY in my terminal (it is empty).
- If I start the server with a clean environment (e.g., env -u API_KEY python server.py), it works. If I start it normally, the wrong value comes back.
- No export API_KEY=... in my shell config files.
Environment:
- macOS
- Python 3.x
- FastAPI
- python-dotenv
Running with uvicorn server:app --reload
Work around
Used load_dotenv(dotenv_path=env_path, override=True) (Works fine but need to know reason why it happens).
unset API_KEYload_dotenvand see if it doesn't load something else before your.envos.getenv(API_KEY)without runningload_dotenv? maybe this value is set by FastAPI or other tools before you even runload_dotenv