Skip to content

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.

15 min read0/4 questions

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=false arrives as the text "false", and any non-empty string is truthy in Python.
  • They can be missing. os.environ["DATABASE_URL"] raises KeyError at whatever moment that line first runs, which may be the first request in production rather than at startup.
Predict the outputPython

The shell has DEBUG=false. What does this print?

import os
os.environ["DEBUG"] = "false"
print(bool(os.environ["DEBUG"]))
Need a nudge? Hints walk you through it.

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.

Pythonmini_settings.py
from dataclasses import dataclass, fields @dataclassclass Settings: database_url: str debug: bool = False pool_size: int = 5 def parse_dotenv(text): pairs = {} for line in text.splitlines(): line = line.strip() if line and not line.startswith("#"): key, _, value = line.partition("=") pairs[key.strip()] = value.strip() return pairs def convert(kind, raw): if kind is bool: return raw.lower() in {"1", "true", "yes", "on"} return kind(raw) def load(dotenv_text, environ, **overrides): sources = [parse_dotenv(dotenv_text), environ] # later wins values = {} for f in fields(Settings): for source in sources: if f.name.upper() in source: values[f.name] = convert(f.type, source[f.name.upper()]) values.update(overrides) return Settings(**values) dotenv = """# local developmentDATABASE_URL=sqlite:///dev.dbDEBUG=true""" print(load(dotenv, {}))print(load(dotenv, {"POOL_SIZE": "20", "DEBUG": "false"}))print(load(dotenv, {}, database_url="sqlite://"))try: load("", {})except TypeError as err: print("startup failed:", err)
Output
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.

app/core/config.py
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()
.env
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 field debug is read from APP_DEBUG. Prefixes stop collisions with variables other tools set, like DEBUG or PORT. Names match case-insensitively by default.
  • env_nested_delimiter="__" lets one variable reach inside a nested model: APP_DB__URL sets db.url, and APP_DB__POOL_SIZE=20 sets db.pool_size. Grouping related settings keeps a growing config readable.
  • Complex types like list[str] are parsed from JSON text, which is why APP_ALLOWED_ORIGINS holds a JSON array.
  • Validators work exactly as in any Pydantic model. field_validator checks one value, and model_validator(mode="after") checks rules that involve several fields, like "no debug mode in production".
  • Literal[...] turns a typo like APP_ENVIRONMENT=prod into a clear error instead of a silent fallback.
  • SecretStr shows 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.

Quick check
With env_prefix set to APP_ and env_nested_delimiter set to __, which variable sets settings.db.pool_size?
Need a nudge? A hint rules out a wrong answer.

Where values come from

When the same setting is defined in several places, pydantic-settings applies a fixed priority:

Settings sources, highest priority first
  1. Arguments to Settings(...)explicit values, mostly in tests
  2. Environment variablesset by the shell, Docker or the platform
  3. .env filelocal development values
  4. Secrets directoryone file per secret, like /run/secrets
  5. Field defaultsdebug: bool = False

Defaults in the class are the fallback. Give defaults only to values that are safe everywhere; leave secrets and URLs required.

1/5

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.

EnvironmentWhere the values come from
Local.env (ignored by git), copied from the committed .env.example
TestsExplicit Settings(...) or monkeypatch.setenv in fixtures
CIVariables and secrets defined in the CI system
Staging, productionThe 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. .env goes in .gitignore; .env.example with 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 with ENV or COPY .env.
Quick check
A teammate pushed a commit containing the production SECRET_KEY, then pushed a second commit deleting it. What is the right fix?
Need a nudge? A hint rules out a wrong answer.

Injecting settings with a cached dependency

You learned dependency injection in the previous lesson. Settings are a perfect fit:

app/api/deps.py
from typing import Annotated
 
from fastapi import Depends
 
from app.core.config import Settings, get_settings
 
SettingsDep = Annotated[Settings, Depends(get_settings)]
app/api/routes/meta.py
@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:

tests/conftest.py
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.

Put it in order5 steps

Order what happens when the app starts with get_settings() called in the lifespan handler.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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=value lines 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.