Difficulty: Intermediate
How do you manage configuration and environment variables in FastAPI?
The recommended approach is pydantic-settings (BaseSettings). It automatically reads from environment variables and .env files, validates them using Pydantic, and provides type-safe access.
BaseSettings fields:
.env file if configuredUse @lru_cache on the settings function so the .env file is only parsed once, or use FastAPI's Depends with caching.
# config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
from functools import lru_cache
class Settings(BaseSettings):
app_name: str = "MyApp"
database_url: str
secret_key: str
debug: bool = False
max_connections: int = 10
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
@lru_cache
def get_settings() -> Settings:
return Settings()
# main.py
from fastapi import FastAPI, Depends
from config import Settings, get_settings
app = FastAPI()
@app.get("/info")
def app_info(settings: Settings = Depends(get_settings)):
return {"app": settings.app_name, "debug": settings.debug}
pydantic-settings, BaseSettings, environment variables, .env