| name | fastapi-settings |
| description | Set up pydantic-settings configuration for a FastAPI project with environment variables, .env file support, and dependency injection. |
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-settings is 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_name: str = "My API"
debug: bool = False
database_url: str
secret_key: str
access_token_expire_minutes: int = 30
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.example with 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