python-dotenv


"/home/yossef/notes/full-stack/python-backend/fastapi/python-dotenv.md"

path: full-stack/python-backend/fastapi/python-dotenv.md

- **fileName**: python-dotenv
- **Created on**: 2025-04-15 13:22:04

who to load .env file in fast api code

## most simple example
## and most common way
import os
from fastapi import FastAPI
from dotenv import load_dotenv

load_dotenv()

foo=os.getenv("FOO_KEY")

app = FastAPI()

@app.get("/")
def home():
    print(foo)
    return {"message":"welcome in home page"}

If the .env and file not at the same folder structure

project/
├── src/
│   └── my_script.py
└── .env
import os
import sys
from dotenv import load_dotenv

## return one folder up
env_dir = os.path.join(os.path.dirname(__file__), '..')
sys.path.append(env_dir)

load_dotenv() # Now it might find .env in the added path

api_key = os.environ.get("API_KEY")
print(f"API Key: {api_key}")

# It's good practice to remove the added path after loading 
if env_dir in sys.path:
    sys.path.remove(env_dir)

continue:[[]]
before:./http-exception.md