Skip to course content
Free FastAPI backend course

FastAPI for AI Backend Development

Unit 02.02: Settings from the environment, typed

Typed settings fail at startup rather than at the first request that needs them.

Environment in, validated, once

A settings class with types, a bound and a fake default.

The code reads it and then feeds it a bad value.

import os
from pydantic import Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    app_name: str = "classifier"
    model_name: str = "fake-model-for-tests"
    max_input_chars: int = Field(default=4000, gt=0)
    api_key: str = ""


os.environ["MAX_INPUT_CHARS"] = "8000"
settings = Settings()
print(f"app_name        {settings.app_name}")
print(f"model_name      {settings.model_name}   <- fake by default")
print(f"max_input_chars {settings.max_input_chars}  <- from the environment")
print(f"api_key set     {bool(settings.api_key)}")

os.environ["MAX_INPUT_CHARS"] = "not a number"
try:
    Settings()
except Exception as exc:
    print(f"\nbad value rejected at startup: {type(exc).__name__}")

# Typed settings fail at startup rather than at the first request that uses
# them. The fake default means a misconfigured environment fails in tests
# instead of silently calling a paid API.

The bad value is rejected when the settings object is built, which is at startup - so a misconfigured deployment fails immediately and visibly rather than at 3am on the first request that reads that field.

The fake model default is deliberate. A missing environment variable then produces a fake rather than a crash, and the test suite runs with nothing configured.

The mistake this prevents

The mistake is reading configuration with os.environ.get at the point of use. Every read is untyped, unvalidated and unfindable, and a typo in a variable name silently produces None.

Takeaway

Declare settings as a typed class read once at startup, with safe defaults. Configuration errors then fail at boot, not on a request.