Full answer
Configuration differs per environment (local, staging, production): database URLs, API keys, feature flags, CORS origins. The twelve-factor approach stores it in environment variables.
pydantic-settings (a separate package since Pydantic v2) turns those variables into a validated object:
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="CAMPUS_", env_file=".env")
database_url: str
debug: bool = False
allowed_origins: list[str] = []
sms_api_key: SecretStrWhat it gives you:
- Type conversion:
CAMPUS_DEBUG=truebecomesTrue;CAMPUS_ALLOWED_ORIGINS='["https://a.edu"]'becomes a list (complex types are parsed as JSON). - Validation at startup: a missing required variable stops the app immediately with a clear error, instead of failing at 2 a.m. on the first request that needs it.
- Priority: init arguments > environment variables >
.envfile > defaults. SecretStrhides values in logs andrepr; call.get_secret_value()where needed.env_nested_delimiter="__"mapsCAMPUS_DB__POOL_SIZEto nested models.- Secrets directories (
secrets_dir="/run/secrets") read Docker or Kubernetes secret files.
Using it in FastAPI:
@lru_cache
def get_settings() -> Settings:
return Settings()
def endpoint(settings: Annotated[Settings, Depends(get_settings)]): ...lru_cache means the environment is read once. In tests, app.dependency_overrides[get_settings] = lambda: Settings(database_url="sqlite://", ...).
Rules: commit a .env.example with placeholder values, never the real .env; load secrets from a secret manager in production; do not log the settings object without SecretStr protection; keep one settings class (or a few nested ones), not scattered os.getenv calls.
import os
from functools import lru_cache
from typing import Annotated
from fastapi import Depends, FastAPI
from fastapi.testclient import TestClient
from pydantic import SecretStr, ValidationError
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_prefix="CAMPUS_")
database_url: str
debug: bool = False
allowed_origins: list[str] = []
max_upload_mb: int = 5
sms_api_key: SecretStr
try:
Settings()
except ValidationError as e:
print("missing at startup:", sorted(err["loc"][0] for err in e.errors()))
os.environ.update({
"CAMPUS_DATABASE_URL": "postgresql+psycopg://app@db/campus",
"CAMPUS_DEBUG": "true",
"CAMPUS_ALLOWED_ORIGINS": '["https://app.college.edu"]',
"CAMPUS_SMS_API_KEY": "sk-demo-123",
})
@lru_cache
def get_settings() -> Settings:
return Settings()
app = FastAPI()
@app.get("/config")
def config(settings: Annotated[Settings, Depends(get_settings)]):
return {"debug": settings.debug, "origins": settings.allowed_origins,
"max_upload_mb": settings.max_upload_mb, "key_repr": repr(settings.sms_api_key)}
c = TestClient(app)
print(c.get("/config").json())
app.dependency_overrides[get_settings] = lambda: Settings(database_url="sqlite://", sms_api_key="test",
max_upload_mb=1)
print(c.get("/config").json()["max_upload_mb"])
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Requires `pip install pydantic-settings`. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): missing at startup: ['database_url', 'sms_api_key'] {'debug': True, 'origins': ['https://app.college.edu'], 'max_upload_mb': 5, 'key_repr': "SecretStr('**********')"} 1
Key points
- BaseSettings reads and validates environment variables
- Missing required settings fail at startup
- Priority: init args > env vars > .env > defaults
- SecretStr hides secret values
- Cached get_settings dependency, overridable in tests
Common mistakes
- Scattering os.getenv calls with no validation across the code
- Importing BaseSettings from pydantic (v1 location) instead of pydantic-settings
- Committing the real .env file
- Logging settings objects that contain plain-string secrets
- Creating Settings() on every request instead of caching
Follow-ups
- How would you load secrets from a cloud secret manager into settings?
- How do you override settings in tests?
- Why fail at startup instead of at first use?
Tips
- Show the cached dependency pattern
- Mention SecretStr and the priority order
- Talk about .env.example and secret managers