Production DeploymentLesson 6.2
How to manage environment variables and secrets in FastAPI production
pydantic-settings, BaseSettings, env file loading, Settings singleton, get_settings dependency, secret injection, dotenv validation, environment-specific config
Environment Variables with pydantic-settings
pydantic-settings provides a BaseSettings class that reads environment variables and validates them with Pydantic types — the same way models validate request data.
Install and define settings
pip install pydantic-settings# config.py
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
secret_key: str
algorithm: str = "HS256"
access_token_expire_minutes: int = 30
debug: bool = False
class Config:
env_file = ".env"
_settings = None
def get_settings() -> Settings:
global _settings
if _settings is None:
_settings = Settings()
return _settings
Inject settings as a dependency
from fastapi import Depends
from .config import get_settings, Settings
@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
return {"debug": settings.debug}
In tests, override get_settings with a dependency that returns a test configuration. In production, set environment variables directly — never commit .env to version control. If database_url is missing, Pydantic raises a validation error at startup rather than failing on the first request.
