Course map
Stage 1: Foundations
Stage 2: Data Integration
Stage 3: Building & Shipping
Stage 4: Customer Engagement
Stage 5: Specialization

Part 10 / Topic 2 of 6

Validating config at startup

A service that starts with a missing token fails hours later, at the first API call, at night, as a confusing 401 in someone else's logs. A service that validates config at startup fails at deploy time, in front of the person deploying, with the fix in the message. Same Pydantic you used on data, now on settings:

# examples/01_configuration_from_environment_variables_that_fails.py
import os
from pydantic import BaseModel, Field, ValidationError

class Settings(BaseModel):
    acme_api_url: str = Field(pattern=r"^https://")
    acme_api_token: str = Field(min_length=10)
    page_size: int = Field(default=100, ge=1, le=1000)
    environment: str = Field(pattern=r"^(dev|staging|prod)$")

def load_settings(env):
    return Settings(acme_api_url=env.get("ACME_API_URL", ""), acme_api_token=env.get("ACME_API_TOKEN", ""),
                    page_size=env.get("PAGE_SIZE", 100), environment=env.get("APP_ENV", ""))

good = {"ACME_API_URL": "https://api.acme.example", "ACME_API_TOKEN": "x" * 24, "APP_ENV": "prod"}
s = load_settings(good)
print("loaded:", s.environment, s.acme_api_url, "token length", len(s.acme_api_token))

bad = {"ACME_API_URL": "http://api.acme.example", "PAGE_SIZE": "5000", "APP_ENV": "production"}
try:
    load_settings(bad)
except ValidationError as e:
    for err in e.errors():
        print("config error:", err["loc"][0], "-", err["msg"])
# loaded: prod https://api.acme.example token length 24
# config error: acme_api_url - String should match pattern '^https://'
# config error: acme_api_token - String should have at least 10 characters
# config error: page_size - Input should be less than or equal to 1000
# config error: environment - String should match pattern '^(dev|staging|prod)$'

Four errors, each named, all at once — the operator fixes the whole file in one pass instead of playing whack-a-mole. Notice the rules encode policy, not just types: https:// only, tokens of plausible length, page sizes the API will accept, environments from a closed list (production is a typo, and the validator caught it).

🧪 Quick quiz — answer from memory, then check.

  1. Why should an app validate its configuration at startup and refuse to start if it is wrong?
Show the answer

A clear error at deploy time beats a confusing failure hours later in production. The bad config produced four named errors at once. (verified against the example output above)

Done here? The practice set for Part 10 — 4 exercises with solutions — is on the part page.

Search the guide