1

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).

6
  • Have you tried unset API_KEY Commented Jul 25 at 21:33
  • maybe you could check source code for load_dotenv and see if it doesn't load something else before your .env Commented Jul 28 at 23:51
  • did you check what you get os.getenv(API_KEY) without running load_dotenv? maybe this value is set by FastAPI or other tools before you even run load_dotenv Commented Jul 28 at 23:53
  • Yes, tried everything Commented Aug 29 at 6:20
  • have you tried adding quotes around api key? sometimes, they contain some special characters and can break dotenv. try single and double quotes. Commented Sep 3 at 14:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.