Course contentsShow
← Python
Lesson 547 of 1,0608. Professional Tooling and PackagingFree lesson

Defining Configuration Schemas with Pydantic Settings

Create type-safe configuration models that validate environment variables at runtime to catch missing or incorrectly formatted settings early.

In this lesson, you’ll learn how to replace fragile, manual environment variable parsing with type-safe, validated configuration models using Pydantic Settings.

Why Configuration Schemas Matter

As your application grows, managing environment variables like DATABASE_URL or API_KEY becomes error-prone. Accessing them using os.environ returns strings, meaning you have to manually convert types, handle missing values, and validate formats every time you use them. A Pydantic Settings model automates this by treating your environment as a strongly-typed schema that is validated the moment your application starts.

Defining Your Settings Model

Instead of sprinkling os.getenv calls throughout your code, you define a class that inherits from BaseSettings. Pydantic automatically maps uppercase environment variables to your class attributes.

from pydantic import Field
from pydantic_settings import BaseSettings

class AppConfig(BaseSettings):
    app_name: str = "MyService"
    debug_mode: bool = False
    port: int = Field(default=8080, ge=1024, le=65535)
    database_url: str

# Instantiate the settings
config = AppConfig()

print(f"Starting {config.app_name} on port {config.port}...")

How it Works

When you instantiate AppConfig, Pydantic performs the following:

  1. Validation: It checks if port is an integer and debug_mode is a boolean. If you provide PORT="abc", it raises a ValidationError immediately at startup.
  2. Type Casting: It converts the string "8080" from the environment into the Python integer 8080.
  3. Requirement Checking: If database_url is not provided in your environment variables, Pydantic throws an error, preventing your app from entering a broken state.
  4. Constraints: Using Field(ge=1024), we enforce that the port must be a valid, non-privileged port number.

By centralizing these settings into a schema, you ensure that any configuration error is caught as soon as the process launches, rather than deep within your business logic hours later.

Key Takeaway: Pydantic Settings transforms loose environment variables into a strictly typed, validated schema, allowing you to catch configuration errors at startup rather than during runtime.