Load typed settings from .env using Pydantic BaseSettings with @lru_cache for efficiency.
Settings with Pydantic
from pydantic_settings import BaseSettings, SettingsConfigDict
from functools import lru_cache
class Settings(BaseSettings):
app_name: str = "My API"
debug: bool = False
database_url: str
secret_key: str
redis_url: str = "redis://localhost:6379"
cors_origins: list[str] = ["http://localhost:3000"]
jwt_expire_minutes: int = 60
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
case_sensitive=False,
)
# Cached settings — only read once
@lru_cache()
def get_settings() -> Settings:
return Settings()
# Use as dependency
@app.get("/info")
def app_info(settings: Settings = Depends(get_settings)):
return {"app": settings.app_name, "debug": settings.debug}