Settings with pydantic-settings
Config# pip install pydantic-settings
from pydantic_settings import BaseSettings, SettingsConfigDict
from functools import lru_cache
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
app_name: str = "My API"
debug: bool = False
database_url: str
secret_key: str
redis_url: str = "redis://localhost:6379"
allowed_origins: list[str] = ["https://rte.dev"]
@lru_cache
def get_settings() -> Settings:
return Settings()
# Inject in routes/deps
@app.get("/info")
async def info(settings: Settings = Depends(get_settings)):
return {"app": settings.app_name}Tip: The inner class Config is the old Pydantic v1 way; v2 uses model_config = SettingsConfigDict(...). The lru_cache decorator means the environment is read once, not on every request.