0
0
FastapiHow-ToBeginner · 3 min read

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-dotenv or pydantic before use.
  • Forgetting to create or place the .env file in the project root.
  • Not calling load_dotenv() if using python-dotenv.
  • Using os.environ['VAR'] without checking if the variable exists, which can cause errors.
  • Committing sensitive .env files to public repositories.

Wrong way:

import os
print(os.getenv('SECRET_KEY'))  # None if .env not loaded

Right 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 into os.environ
  • Pydantic BaseSettings: Define a class with fields and set env_file = ".env" in Config
  • Access variables: Use os.getenv('VAR') or settings.var from BaseSettings
  • Security: Never commit .env with 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.