Introduction
Modern Python applications often rely on configuration files to manage settings like database connections, application features, and environment-specific parameters. Popular formats include YAML and TOML because they are human-readable and easy to maintain. However, these files are prone to errors, like missing fields or invalid types, which can cause runtime crashes.
This article demonstrates how to use Pydantic, a Python data validation library, to validate YAML and TOML configurations — from basic usage to advanced production-ready techniques.
Understanding the Problem
Suppose we have a configuration file for the application:
app:
name: MyApp
version: 1.0
database:
host: localhost
port: 5432
enabled: trueWithout validation:
A typo in
port("5432a") would crash the app.Missing keys like
databasewould cause runtime errors.Invalid types (
enabled: "yes") could lead to unexpected behavior.
Goal: Automatically verify that all required fields exist, are of the correct type, and meet any constraints.
Introduction to Pydantic
Pydantic provides:
Type enforcement: Ensures the right type for each field
Field validation: Enforces constraints like value ranges
Nested models: Supports structured, hierarchical configs
Fail-fast validation: Errors are raised immediately if something is wrong
Basic Pydantic example:
from pydantic import BaseModel
class AppConfig(BaseModel):
name: str
version: float
app = AppConfig(name="MyApp", version=1.0)Loading YAML and TOML in Python
Python libraries:
YAML: Use
PyYAML(pip install pyyaml)TOML: Python 3.11+ has built-in
tomllib
import yaml
import tomllibDefining Pydantic Models for Configuration
Suppose your config has two sections: add and database
from pydantic import BaseModel, Field
class AppConfig(BaseModel):
name: str
version: float
class DatabaseConfig(BaseModel):
host: str
port: int = Field(gt=0, lt=65536) # port must be between 1-65535
enabled: bool
class Settings(BaseModel):
app: AppConfig
database: DatabaseConfigField (gt=0, lt=65536) ensures the port is valid.
Nested models enforce structure ( app and database).
Loading and Validating YAML
def load_yaml(file_path: str) -> Settings:
with open(file_path, "r") as f:
data = yaml.safe_load(f)
return Settings.model_validate(data) # Pydantic v2Example usage:

Join the conversation! Your thoughts help the community grow.