Set Up FastAPI Settings
When to Use
Use this skill when a FastAPI project has hardcoded configuration or needs environment-based settings.
Instructions
Check if
pydantic-settingsis installed. If not, suggest adding it.Generate the Settings class:
from pydantic_settings import BaseSettings, SettingsConfigDict from functools import lru_cache class Settings(BaseSettings): # App app_name: str = "My API" debug: bool = False # Database database_url: str # Auth secret_key: str access_token_expire_minutes: int = 30 # External services redis_url: str = "redis://localhost:6379" model_config = SettingsConfigDict( env_file=".env", env_file_encoding="utf-8", case_sensitive=False, ) @lru_cache def get_settings() -> Settings: return Settings()Generate
.env.examplewith all required variables.Set up dependency injection:
from typing import Annotated from fastapi import Depends SettingsDep = Annotated[Settings, Depends(get_settings)]Show how to override in tests:
def get_settings_override(): return Settings(database_url="sqlite+aiosqlite:///:memory:") app.dependency_overrides[get_settings] = get_settings_override
Source: RoninForge/roninforge-fastapi — distributed by TomeVault.