Lesson 12 of 59Building a real API
Settings and Config
Load typed, validated settings from environment variables and .env files with pydantic-settings, keep secrets out of git, and inject config cleanly.
Your API needs a database URL, a secret key for signing tokens, a list of allowed frontend origins, maybe an API key for an email provider. On your laptop those point at local services; in production they point at real ones, and some of them must never be seen by anyone. Hardcode them and you get secrets in git history, a deploy that talks to the dev database, and tests that cannot change a value. This lesson sets up configuration the way production teams do: from the environment, typed and validated at startup, with secrets kept out of the code entirely.
Config lives in the environment
The twelve-factor app guidelines, written for apps that run on cloud platforms, define config as everything that changes between deploys of the same code: database and cache URLs, credentials for outside services, hostnames, feature flags. Their rule is strict separation. Config comes from environment variables, and the code is identical everywhere.
A good test: could you make the repository public right now without leaking a single credential? If not, config is mixed into code.
Environment variables work for every language and every platform. Docker, Kubernetes, GitHub Actions, and every hosting platform know how to set them. They also have two traps:
- They are always strings.
DEBUG=falsearrives as the text"false", and any non-empty string is truthy in Python. - They can be missing.
os.environ["DATABASE_URL"]raisesKeyErrorat whatever moment that line first runs, which may be the first request in production rather than at startup.
The shell has DEBUG=false. What does this print?
import os os.environ["DEBUG"] = "false" print(bool(os.environ["DEBUG"]))
A settings loader, from scratch
Before using a library, here is what one has to do: read a .env file, read the real environment, let the environment win, convert each value to the declared type, and fail early if something required is missing.
Press Run (⌘ Enter) to see what happens.The second line shows the key rule: a real environment variable beats the .env file. That is what lets the same code run on a laptop (values from .env) and in production (values set by the platform). The last line shows the other key rule: a missing required value stops the app when settings load, not halfway through a request.
pydantic-settings
pydantic-settings does all of this with the Pydantic models you already know, plus nested values, prefixes and validators. Install it with uv add pydantic-settings.
from functools import lru_cache
from typing import Literal
from pydantic import BaseModel, SecretStr, field_validator, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
class DatabaseSettings(BaseModel):
url: str
pool_size: int = 5
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_file=".env",
env_prefix="APP_",
env_nested_delimiter="__",
extra="ignore",
)
environment: Literal["local", "test", "staging", "production"] = "local"
debug: bool = False
db: DatabaseSettings
secret_key: SecretStr
allowed_origins: list[str] = []
@field_validator("secret_key")
@classmethod
def long_enough(cls, value: SecretStr) -> SecretStr:
if len(value.get_secret_value()) < 32:
raise ValueError("must be at least 32 characters")
return value
@model_validator(mode="after")
def safe_in_production(self) -> "Settings":
if self.environment == "production" and self.debug:
raise ValueError("debug must be off in production")
return self
@lru_cache
def get_settings() -> Settings:
return Settings()APP_ENVIRONMENT=localAPP_DEBUG=trueAPP_DB__URL=postgresql+psycopg://app:app@localhost:5432/todosAPP_SECRET_KEY=local-dev-only-0123456789abcdef0123456789APP_ALLOWED_ORIGINS=["http://localhost:5173"]What each piece does:
env_prefix="APP_"means the fielddebugis read fromAPP_DEBUG. Prefixes stop collisions with variables other tools set, likeDEBUGorPORT. Names match case-insensitively by default.env_nested_delimiter="__"lets one variable reach inside a nested model:APP_DB__URLsetsdb.url, andAPP_DB__POOL_SIZE=20setsdb.pool_size. Grouping related settings keeps a growing config readable.- Complex types like
list[str]are parsed from JSON text, which is whyAPP_ALLOWED_ORIGINSholds a JSON array. - Validators work exactly as in any Pydantic model.
field_validatorchecks one value, andmodel_validator(mode="after")checks rules that involve several fields, like "no debug mode in production". Literal[...]turns a typo likeAPP_ENVIRONMENT=prodinto a clear error instead of a silent fallback.SecretStrshows as**********when printed or logged. Code that needs the real value calls.get_secret_value().
If anything is missing or invalid, creating Settings() raises a ValidationError listing every problem at once, before the app accepts a single request. A deploy with a bad config fails its health check and never receives traffic.
env_prefix set to APP_ and env_nested_delimiter set to __, which variable sets settings.db.pool_size?Where values come from
When the same setting is defined in several places, pydantic-settings applies a fixed priority:
Defaults in the class are the fallback. Give defaults only to values that are safe everywhere; leave secrets and URLs required.
One detail surprises people: pydantic-settings reads .env for your Settings class only. It does not copy those values into os.environ, so a library that reads os.environ itself will not see them. Pass the value from your settings object to the library instead.
You can list several files, env_file=(".env", ".env.local"), and later files win. Teams use that to commit shared, non-secret defaults and keep personal overrides in an ignored file.
Different settings per environment
The twelve-factor way is one Settings class and different values, not different code per environment. Local, CI, staging and production all run the same image; only their environment variables differ.
| Environment | Where the values come from |
|---|---|
| Local | .env (ignored by git), copied from the committed .env.example |
| Tests | Explicit Settings(...) or monkeypatch.setenv in fixtures |
| CI | Variables and secrets defined in the CI system |
| Staging, production | The platform's settings or a secret manager |
Resist sprinkling if settings.environment == "production": through the code. Each branch is behaviour you cannot test locally. Prefer a specific setting for each behaviour, like send_real_emails: bool or log_json: bool, and set it per environment. Then the environment field is mostly for labels in logs and error reports, plus a few safety validators like the one above.
Secrets
Secrets are the subset of config that grants access: database passwords, signing keys, API tokens.
- Never commit them.
.envgoes in.gitignore;.env.examplewith fake values is committed so teammates know what to set. - If one is committed, rotate it. Deleting the line, or even rewriting git history, is not enough: clones, forks and CI logs may already have it. Issue a new key and revoke the old one. Secret scanners (GitHub's built-in scanning, or gitleaks as a pre-commit hook) catch many leaks before they happen.
- In production, use the platform's secret store. Hosting platforms have encrypted environment settings, and clouds have secret managers (AWS Secrets Manager, Google Secret Manager, HashiCorp Vault, Doppler). They inject secrets as environment variables or mounted files at runtime, control who can read them, and keep an audit trail.
- Never log the whole settings object unless every secret field is a
SecretStr, and do not bake secrets into Docker images withENVorCOPY .env.
SECRET_KEY, then pushed a second commit deleting it. What is the right fix?Injecting settings with a cached dependency
You learned dependency injection in the previous lesson. Settings are a perfect fit:
from typing import Annotated
from fastapi import Depends
from app.core.config import Settings, get_settings
SettingsDep = Annotated[Settings, Depends(get_settings)]@router.get("/meta")
def meta(settings: SettingsDep) -> dict[str, str]:
return {"environment": settings.environment}@lru_cache on get_settings means the environment is read and validated once, on the first call; after that every request gets the same object for free. Call get_settings() in your lifespan handler or at startup too, so a broken config fails the deploy immediately rather than on the first request.
Why not just write settings = Settings() at module level and import it everywhere? It works, but it runs on import, so merely importing the module (in a test, a migration script, or your editor's analyzer) needs a full, valid environment. Tests also cannot swap it. With a function, tests have two clean options:
import pytest
from app.core.config import Settings, get_settings
from app.main import app
@pytest.fixture
def test_settings():
settings = Settings(
_env_file=None, # ignore the developer's .env
environment="test",
db={"url": "sqlite://"},
secret_key="test-" + "x" * 40,
)
app.dependency_overrides[get_settings] = lambda: settings
yield settings
app.dependency_overrides.clear()_env_file=None matters: without it, a test run quietly picks up whatever is in the developer's own .env, and passes on one laptop but not another. The other option, for code that calls get_settings() directly, is monkeypatch.setenv("APP_DEBUG", "false") followed by get_settings.cache_clear(), so the next call rebuilds from the patched environment.
Order what happens when the app starts with get_settings() called in the lifespan handler.
- Tap the steps below in the right order.
- twelve-factor config
- The rule that anything varying between deploys comes from environment variables, never from code.
- environment variable
- A named string value set for a process by its shell or platform, read in Python through
os.environ. - .env file
- A local, uncommitted file of
KEY=valuelines used to fill settings during development. - BaseSettings
- The pydantic-settings base class that builds a typed, validated object from the environment and
.env. - SecretStr
- A Pydantic type that hides its value when printed; read it with
.get_secret_value(). - secret rotation
- Replacing a credential with a new one and revoking the old, the only real fix for a leak.