How to Use .env File with FastAPI for Configuration
To use a
.env file with FastAPI, install python-dotenv or use Pydantic's BaseSettings class to load environment variables automatically. Place your variables in a .env file, then load them in your FastAPI app to keep configuration separate from code.Syntax
Use the python-dotenv package or Pydantic's BaseSettings to load environment variables from a .env file.
With python-dotenv, call load_dotenv() early in your app to load variables into os.environ.
With Pydantic, create a settings class inheriting from BaseSettings, which reads variables automatically.
python
from dotenv import load_dotenv import os load_dotenv() # Loads variables from .env into os.environ SECRET_KEY = os.getenv('SECRET_KEY') # OR using Pydantic from pydantic import BaseSettings class Settings(BaseSettings): secret_key: str class Config: env_file = ".env" settings = Settings() print(settings.secret_key)
Example
This example shows how to create a .env file, load it with Pydantic's BaseSettings, and use the variables in a FastAPI app.
python
# .env file content (create this file in your project root) # SECRET_KEY=mysecret123 from fastapi import FastAPI from pydantic import BaseSettings class Settings(BaseSettings): secret_key: str class Config: env_file = ".env" settings = Settings() app = FastAPI() @app.get("/") async def read_secret(): return {"secret_key": settings.secret_key} # Run with: uvicorn filename:app --reload
Output
{"secret_key":"mysecret123"}
Common Pitfalls
- Not installing
python-dotenvorpydanticbefore use. - Forgetting to create or place the
.envfile in the project root. - Not calling
load_dotenv()if usingpython-dotenv. - Using
os.environ['VAR']without checking if the variable exists, which can cause errors. - Committing sensitive
.envfiles to public repositories.
Wrong way:
import os
print(os.getenv('SECRET_KEY')) # None if .env not loadedRight way with python-dotenv:
from dotenv import load_dotenv
import os
load_dotenv()
print(os.getenv('SECRET_KEY'))python
from dotenv import load_dotenv import os # Wrong: no load_dotenv call print(os.getenv('SECRET_KEY')) # Likely None # Right: load_dotenv() print(os.getenv('SECRET_KEY')) # Correct value if .env exists
Output
None
mysecret123
Quick Reference
- .env file: Store key=value pairs, e.g.,
SECRET_KEY=mysecret123 - python-dotenv: Call
load_dotenv()to load variables intoos.environ - Pydantic BaseSettings: Define a class with fields and set
env_file = ".env"in Config - Access variables: Use
os.getenv('VAR')orsettings.varfrom BaseSettings - Security: Never commit
.envwith secrets to public repos
Key Takeaways
Use Pydantic BaseSettings with env_file for clean, automatic .env loading in FastAPI.
Call load_dotenv() early if using python-dotenv to load environment variables.
Keep your .env file in the project root and never commit secrets publicly.
Access environment variables safely using os.getenv or BaseSettings attributes.
Ensure required packages like python-dotenv or pydantic are installed before use.