Skip to main content

How to Validate a YAML Settings File in Python with pydantic

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

A settings file is only as good as the values in it. A port typed as 80800 or a setting written as maybe should stop the program when it starts, with a message that names the setting, not crash it later somewhere else. Loading the YAML with PyYAML and checking it with pydantic models does exactly that. This guide builds it with pydantic 2.14.4 and PyYAML 6.0.4 on Python 3.15.2.

Syntax​

Syntax
with open("<file>.yaml", encoding="utf-8") as file:
<settings> = <Settings>.model_validate(yaml.safe_load(file))
PartWhat it means
yaml.safe_load(file)Reads the YAML into dictionaries, text and numbers
<Settings>A pydantic model that describes every setting, its type and its limits
.model_validate(...)Checks the dictionary against the model, and raises a ValidationError listing every wrong value

pydantic's models guide says that with model_validate(), "data can be provided either as a dictionary, or as a model instance".

The Example​

A small server reads settings.yaml: a server section with a host and a port, and a debug switch. The port must be between 1 and 65535.

Prerequisites​

  • pydantic and PyYAML in your project, for example with uv add pydantic pyyaml. This guide uses pydantic 2.14.4 and PyYAML 6.0.4 on Python 3.15.2.

Step 1: Write the Settings File​

settings.yaml
server:
host: 127.0.0.1
port: 8000
debug: false

settings.yaml in a macOS-style code window: a server section with host 127.0.0.1 and port 8000, and debug: false.

Step 2: Describe the Settings with Models​

One model per section, with the same names as the keys in the file. Field(ge=1, le=65535) sets the port's limits.

settings.py
from pathlib import Path

import yaml
from pydantic import BaseModel, Field


class Server(BaseModel):
host: str
port: int = Field(ge=1, le=65535)


class Settings(BaseModel):
server: Server
debug: bool


def load_settings(path: Path) -> Settings:
with path.open(encoding="utf-8") as file:
return Settings.model_validate(yaml.safe_load(file))


settings = load_settings(Path("settings.yaml"))
print(settings)
print("Listening on", settings.server.host, "port", settings.server.port)

settings.py in a macOS-style code window: a Server model with host and a port limited to 1 to 65535, a Settings model with server and debug, and a load_settings function that validates yaml.safe_load output with Settings.model_validate.

Step 3: Run It​

Terminal
uv run python settings.py
Output
server=Server(host='127.0.0.1', port=8000) debug=False
Listening on 127.0.0.1 port 8000

The terminal after uv run python settings.py: server=Server(host='127.0.0.1', port=8000) debug=False, then Listening on 127.0.0.1 port 8000.

The server section became a Server object, so settings.server.port reads with dots, and debug is a real False. The command works unchanged in PowerShell.

Step 4: See a Wrong Value Stop It​

Change two values in settings.yaml: port: 80800, too high, and debug: maybe. Run the script again. It stops, and the last lines of the traceback list both problems:

Output (last lines)
pydantic_core._pydantic_core.ValidationError: 2 validation errors for Settings
server.port
Input should be less than or equal to 65535 [type=less_than_equal, input_value=80800, input_type=int]
For further information visit https://errors.pydantic.dev/2.14/v/less_than_equal
debug
Input should be a valid boolean, unable to interpret input [type=bool_parsing, input_value='maybe', input_type=str]
For further information visit https://errors.pydantic.dev/2.14/v/bool_parsing

The last lines of the traceback: 2 validation errors for Settings, server.port should be less than or equal to 65535, and debug should be a valid boolean.

Each error gives the setting's path in the file, server.port and debug, the rule it broke and the value it had. Put the two values back before you go on.

Common Mistakes​

MistakeWhat happensDo this instead
A setting missing from the fileWith no debug line, the error was debug and Field required [type=missing ...]Add the setting, or give the field a default in the model
Reading the YAML with yaml.loadIt can build any Python object a file asks forUse yaml.safe_load

Troubleshooting​

SymptomLikely causeFix
ValidationError with a dotted path such as server.portThat setting is wrong, inside the server sectionFix the value the error names
Input should be a valid booleanA switch has a value pydantic can't read as true or falseWrite true or false

FAQ​

How do I catch misspelled settings?​

Set model_config = ConfigDict(extra="forbid") on each model, so an unknown key is an error instead of being ignored.

Why not check the values myself with if statements?​

Because the models describe every setting in one place, and pydantic reports every wrong value at once, with its path, instead of the first one it meets.

Conclusion​

Settings.model_validate(yaml.safe_load(file)) turned settings.yaml into checked settings, and refused port: 80800 and debug: maybe with one error that named both. Validate settings when the program starts, so a typo never gets further.

Additional Resources​