Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 50 ยท Structuring larger apps

Settings and configuration

Configure FastAPI the 12-factor way: typed settings from environment variables with pydantic-settings, a cached settings dependency, secrets and test overrides.

Every application has values that change between your laptop, the test server and production: the database URL, the allowed web origins, a secret signing key, a feature flag. If you write them into the code, you must edit and redeploy code to change a URL, and sooner or later a password ends up in Git. The well-known rule from the Twelve-Factor App methodology is simple: keep configuration in the environment, not in the code.

FastAPI itself has no settings system, but it works beautifully with Pydantic, whose companion package pydantic-settings reads environment variables into a typed, validated class. In this lesson you will define settings, read them from the environment, hand them to endpoints through a cached dependency, handle secrets with care, and replace them in tests.

Why typed settings?

Environment variables are always strings. Without help you end up with int(os.environ["PORT"]), os.environ.get("DEBUG") == "true" and typos nobody notices until production. A settings class gives you:

  • Types and conversion: "20" becomes the integer 20, "true" becomes True, a JSON list becomes a Python list.
  • Defaults for local development.
  • Validation at startup: a missing or invalid value stops the app immediately with a clear message, instead of failing on the first request at 3 a.m.
  • One place to look when you wonder what the app can be configured with.

pydantic-settings is a separate package (pip install pydantic-settings). In the in-browser examples on this page it is installed with micropip, just like FastAPI. Environment variables are set from Python with os.environ because the sandbox has no real shell; on a server your process manager, Docker or hosting platform sets them.

Defining and reading settings

Subclass BaseSettings, list fields with types and defaults, and Pydantic fills them from environment variables whose names match the field names (case-insensitively). An env_prefix such as DEMO_ keeps your variables apart from everything else in the environment.

Two special types are worth knowing. SecretStr wraps a string so that printing or logging it shows only asterisks; you call .get_secret_value() where you really need the text. And booleans accept the usual spellings (true, 1, yes, on).

Python Settings from environment variables, cached and overridden

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Go through the output:

  • The first line shows conversion: "true" became True and "20" became 20.
  • repr(settings.api_key) prints SecretStr('**********'), so an accidental print(settings) or log line does not leak the key. Only get_secret_value() reveals it.
  • Setting DEMO_MAX_PAGE_SIZE to lots makes Settings() raise a ValidationError that names the field (max_page_size) and the problem (int_parsing). In production this happens at startup, which is what you want.
  • Three requests built the settings once (settings built 1 time(s)). Last, the override gives the endpoint test settings without touching the environment.

The cached settings dependency

Creating Settings() reads the environment and validates everything. You do not want to do that on every request, and you do not want a global variable created at import time either, because then tests cannot swap it. The standard FastAPI pattern is a tiny function wrapped in functools.lru_cache:

Python
from functools import lru_cache

@lru_cache
def get_settings() -> Settings:
    return Settings()

The first call builds the object; later calls return the same one. Endpoints ask for it with Depends(get_settings), and tests replace it with app.dependency_overrides[get_settings], as in the example. This is the dependency pattern from Dependencies applied to configuration.

get_settings is a plain, non-async function, which is what you would write in a normal project (FastAPI runs it in a worker thread, and the cache makes that cost negligible). The browser shim at the top of the example only exists because Pyodide cannot start threads.

Precedence, validation and prefixes

Where does each value come from? pydantic-settings checks several sources and the highest-priority one wins: values passed to Settings(...) directly, then environment variables, then a .env file (if you configured one), then the defaults in the class. The next example shows the layers, plus validation with Field constraints and a custom validator.

Python Defaults, environment, init arguments and validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notes on what you saw:

  • Lists and other complex types are read from environment variables as JSON ('["a", "b"]').
  • Both problems in step 4 were reported together, so one deployment attempt shows every misconfiguration at once.
  • With env_prefix="SHOP_", the field token_minutes is read from SHOP_TOKEN_MINUTES.

A .env file for local development

Typing ten export commands before running the server is tedious. For development, put the values in a file called .env next to your project and tell the settings class to read it (read-only snippet, because the sandbox has no files):

Python
class Settings(BaseSettings):
    model_config = SettingsConfigDict(env_file=".env", env_prefix="SHOP_")
    database_url: str = "sqlite:///./dev.db"
    secret_key: SecretStr
TEXT
# .env  (never commit this file: add it to .gitignore)
SHOP_DATABASE_URL=postgresql://shop:shop@localhost:5432/shop
SHOP_SECRET_KEY=change-me-locally

Real environment variables still beat the .env file, so production can ignore the file entirely.

Handling secrets

  • No secrets in Git. Not in code, not in the committed .env. Commit a .env.example with fake values so teammates know which variables exist.
  • No default for real secrets. secret_key: SecretStr with no default makes the app refuse to start when the variable is missing, instead of silently running with a known key. Defaults like "dev-key" are fine only for harmless development values.
  • Use SecretStr for keys and passwords so logs and error pages do not print them.
  • Inject secrets from the platform: Docker secrets, your host's dashboard, or a secrets manager. The app just reads the environment, and the deployment decides where the values come from. See Deployment.
  • Never expose settings through an endpoint unless you filter them. A debug route that returns the whole settings object is a classic leak.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is Settings() usually wrapped in a function decorated with @lru_cache?

    Building the object reads and validates the environment. The cache avoids repeating that, and keeping it behind a function leaves room to override it in tests.
  2. 2. A value is set in the class default, in a .env file, in a real environment variable and passed as Settings(value=...). Which one wins?

    Priority from highest to lowest is init arguments, environment variables, the .env file, then defaults.
  3. 3. What does printing a SecretStr field show?

    SecretStr masks the value in repr and str, which protects logs from accidental leaks.
  4. 4. How do you pass a list, such as allowed origins, in an environment variable to a list[str] field?

    Complex values are parsed from JSON by default, so a JSON array string becomes a Python list.

Summary

  • Keep configuration in the environment; use pydantic-settings for typed, validated settings.
  • BaseSettings reads variables by field name; env_prefix namespaces them; .env is for local development only.
  • Priority: init arguments, environment, .env file, class defaults.
  • Wrap Settings() in an lru_cache function and inject it with Depends; override it in tests.
  • Use SecretStr, give real secrets no default, and never commit or expose them.

Next: Middleware and CORS covers code that wraps every request and lets browsers call your API from other origins.