FastAPI applications manage configuration with pydantic-settings (BaseSettings) — a class that reads config from environment variables (and .env files) with , keeping secrets out of code and ensuring config is correct at startup.
FastAPI applications manage configuration with pydantic-settings (BaseSettings) — a class that reads config from environment variables (and .env files) with , keeping secrets out of code and ensuring config is correct at startup.
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
app_name: str = "My API"
database_url: str # required — must be provided
secret_key: str # required (a secret)
debug: bool = False
max_connections: int = 10
class Config:
env_file = ".env" # also read from a .env file
settings = Settings() # reads & VALIDATES env vars at startup
BaseSettings automatically reads each field from a matching environment variable (e.g. DATABASE_URL), converts types ("true" → bool, "10" → int), and validates — a missing required value or wrong type fails immediately at startup with a clear error (fail-fast).
from functools import lru_cache
from fastapi import Depends
@lru_cache # create the Settings once (cached)
def get_settings():
return Settings()
@app.get("/info")
def info(settings: Settings = Depends(get_settings)):
return {"app": settings.app_name, "debug": settings.debug}
Injecting settings via a cached dependency makes them testable (override in tests) and ensures a single instance.
# .env — local config, GITIGNORED (never commit secrets)
DATABASE_URL=postgresql://localhost/mydb
SECRET_KEY=dev-secret
DEBUG=true
✓ Keep secrets in env vars / .env (gitignored); commit a .env.example documenting keys
✓ In production, inject config via the platform's environment / secret manager
✓ Validation at startup catches misconfiguration immediately (not deep in a request)
Proper settings management is both an operational necessity (apps need different config across dev/staging/production) and a security requirement (secrets like database URLs and keys must never be hardcoded in source control — a common, serious breach).
Pydantic's BaseSettings provides the idiomatic FastAPI solution, and understanding it is important everyday knowledge.
Its key advantages: reading config from environment variables (keeping secrets out of code, the twelve-factor approach) with automatic type conversion and validation — so misconfiguration fails fast at startup with a clear error rather than as a confusing runtime failure.
Combined with dependency injection (making settings testable and singleton) and the practice of gitignored .env files for local development, this gives you safe, validated, environment-appropriate configuration.
Knowing how to define settings, use them via DI, and handle secrets securely is fundamental for building production-ready FastAPI applications.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate