Skip to Content

Why use Pydantic’s BaseSettings instead of os.environ dictionaries?

Category: Backend & API

Answer

BaseSettings gives you a typed config class that loads once at import time. Each field has a Python type, an env-var binding, a default, and custom validators. Bad config (short secret_key, prod with a default token) raises ValueError before the app can serve a request — never silently.

Concrete examples from the fca project context

Example 1

Settings(env=…) reads DATABASE_URL, JWT_SECRET, LANGFUSE_KEY with typed defaults.

Example 2

@field_validator(“jwt_secret_key”) rejects the placeholder default in prod.

Example 3

settings.environment branches pool kwargs (NullPool for tests, pool_size + pre_ping for prod).

Data flow / flow chart

os.environ -> Settings() -> validators -> typed config
  Any validator failure -> ImportError before startup

Takeaway

Typed config at import time is the cheapest insurance you can buy against bad deploys.