
Pydantic Settings loads application configuration into a typed Python object. A worker count can become an integer, a debug flag can become a boolean, and a missing required value can stop startup before the application accepts work. The useful part is making those rules explicit and checking that the running process receives the values you intended.
This guide uses Pydantic 2.14.3 and pydantic-settings 2.16.3, with examples tested on Python 3.12.14 on Windows. The pinned settings package requires Python 3.11 or later. We will load a small configuration, exercise its source precedence, and separate useful diagnostics from values that should stay out of logs.
Start with required values, acceptable ranges, and defaults you would be comfortable using in a deployed service. A default of two workers may be reasonable for a demonstration; a default production credential is not. Leave the credential required and give numeric settings limits that make sense for your workload.
In an isolated Python environment, install pydantic==2.14.3 and pydantic-settings==2.16.3 with pip. The official settings package is separate from Pydantic. Import BaseSettings from pydantic_settings, then save this as settings.py:
from pydantic import BaseModel, ConfigDict, Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Database(BaseModel):
model_config = ConfigDict(extra="forbid", hide_input_in_errors=True)
host: str = Field(default="localhost", min_length=1)
port: int = Field(default=5432, ge=1, le=65535)
class Settings(BaseSettings):
model_config = SettingsConfigDict(
env_prefix="APP_",
env_nested_delimiter="__",
env_file=None,
case_sensitive=False,
extra="forbid",
hide_input_in_errors=True,
cli_parse_args=False,
)
token: SecretStr = Field(min_length=1)
workers: int = Field(default=2, ge=1, le=32)
debug: bool = False
database: Database = Field(default_factory=Database)
The required token has no default and cannot be empty. Workers must be between 1 and 32, and the database port must be between 1 and 65,535. These are rules for this example, not infrastructure sizing recommendations. The database model validates configuration; it does not establish a database connection or verify that the hostname is reachable.
String conversion is intentional: APP_WORKERS=4 should produce an integer. This model is not in strict mode. Our checks rejected an out-of-range worker count, a nonnumeric count, an invalid boolean, and an invalid nested port.
The example leaves Pydantic's CLI parsing disabled and uses no custom settings sources. For the same worker field, the following order was observed in the tests. Each source supplied a different value so we could check which one won.
| Priority | Source | Test value |
|---|---|---|
| 1, highest | Constructor argument, such as workers=6 | 6 |
| 2 | Process environment: APP_WORKERS | 5 |
| 3 | Explicit dotenv file | 4 |
| 4 | File in the secrets directory | 3 |
| 5, lowest | Model default | 2 |
A deployment environment can therefore override a value in a local dotenv file. Passing a constructor value can override both. Avoid scattering constructor overrides through application code, because the deployment operator may then change an environment variable without changing the effective setting.
The Pydantic Settings documentation covers other sources and customization. Enabling Pydantic CLI parsing or changing source order requires a new precedence check. The small command-line wrapper below only chooses file paths; it does not enable Pydantic's field-value CLI parsing.
Save the following as example.env. Its token is demonstration text, not a credential. Keep real environment files out of source control and container images.
# Demonstration values only. Never use this token in a real service.
APP_TOKEN=demo-token-not-a-credential
APP_WORKERS=4
APP_DEBUG=false
APP_DATABASE={"host":"db.internal","port":5432}
APP_DATABASE__PORT=5433
With this file, database.host becomes db.internal and database.port becomes 5433. The nested APP_DATABASE__PORT value overrides the port inside the JSON object while preserving its host. We also checked that a nested port alone retains the model's default host.
Our settings class does not automatically load a nearby .env. The startup wrapper accepts an explicit path and rejects a requested file that does not exist. Use a path you control, preferably absolute when the working directory can change. The test suite ran the displayed file from another directory and confirmed that a relative path was not silently resolved by searching a parent directory.
Configuration errors depend on the source. Our extra APP_WORKERZ dotenv entry raised a validation error, but the same misspelled name in the process environment was ignored and the worker default remained. An unknown nested member that matched APP_DATABASE__ was rejected by the nested model. Do not treat extra="forbid" as an audit of every environment variable.
We use case-insensitive matching explicitly. Python's Windows environment handling also normalizes variable names. These Windows tests do not establish case-sensitive behavior on Linux; keep names consistent and test the intended target system.
Save this as start_app.py beside settings.py. It constructs settings before invoking the application callback. The callback only prints a permitted worker count; replace it with your application's startup after adopting the validation boundary.
import argparse
import sys
from pathlib import Path
from pydantic import ValidationError
from pydantic_settings import SettingsError
from settings import Settings
def validation_summary(error: ValidationError) -> str:
allowed = {
("token",): "token",
("workers",): "workers",
("debug",): "debug",
("database", "host"): "database.host",
("database", "port"): "database.port",
}
fields = {
allowed.get(tuple(item["loc"]), "configuration")
for item in error.errors(
include_input=False, include_context=False, include_url=False
)
}
return "Invalid settings: " + ", ".join(sorted(fields))
def start_application(settings: Settings) -> int:
# Replace this demonstration callback with application startup.
print(f"Configuration accepted: workers={settings.workers}")
return 0
def main(argv=None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--env-file", type=Path)
parser.add_argument("--secrets-dir", type=Path)
args = parser.parse_args(argv)
try:
if args.env_file is not None and not args.env_file.is_file():
raise OSError("Configuration file unavailable")
if args.secrets_dir is not None and not args.secrets_dir.is_dir():
raise OSError("Secrets directory unavailable")
settings = Settings(
_env_file=args.env_file, _secrets_dir=args.secrets_dir
)
except ValidationError as error:
print(validation_summary(error), file=sys.stderr)
return 2
except (SettingsError, OSError):
print("Cannot load configuration sources", file=sys.stderr)
return 2
return start_application(settings)
if __name__ == "__main__":
raise SystemExit(main())
Run python start_app.py --env-file example.env from the example directory. With no conflicting APP_ environment values, it prints Configuration accepted: workers=4 and exits successfully. Removing the token from all active sources returns exit code 2 and never invokes the application callback.
For secret files, create a directory containing a file named APP_TOKEN whose contents are the token value, then select it with --secrets-dir. Our tests supplied both token and worker count this way. Restrict file access to the account that needs it; loading a file does not establish secure permissions, encryption, or rotation.
Explicit missing paths also stop this wrapper, even if other sources contain valid settings. Malformed complex JSON produces a source-loading error rather than an ordinary field validation error. Both paths are handled before the callback. This is a startup demonstration, not a running web server or a test of dependency availability.
SecretStr helps with display masking. In our run, the test token was absent from the settings representation and default JSON serialization. Calling get_secret_value() returned the original value, as intended. Masking is not encryption, and custom serialization or explicit access can expose it.
hide_input_in_errors hid the supplied input in the text form of our validation error. The structured error.errors() result still contained the raw invalid input. Do not send either a full settings dump or an unfiltered error object to your logs or an API response.
The wrapper extracts errors without input, context, or documentation URLs, then emits only field names from a fixed allowlist. It does not print error messages or arbitrary locations. We tested an unknown input key containing the generated token; the diagnostic returned only configuration. This narrow diagnostic path is the behavior we verified, not a guarantee about every serializer or logging integration.
Use the same discipline in your Python logging setup. Record the failure and approved field labels; inspect actual configuration through a separate access-controlled process.
The accompanying checks use temporary files, generated test values, restored environment variables, and child Python processes. All 47 checks passed with the pinned versions.
| Scenario | Observed result |
|---|---|
| Required and constrained fields | Missing token, empty token and invalid values rejected |
| Source precedence | Constructor > environment > dotenv > secret files > defaults |
| Nested settings | Nested port override preserves other fields |
| Unknown names | Unmatched environment key ignored; tested dotenv and nested keys rejected |
| Startup and diagnostics | Invalid settings block the callback and exit child processes with code 2 |
| Cleanup | Original environment restored; temporary files removed |
The suite also verifies that an existing settings instance keeps its original value after the environment changes, while a newly constructed instance reads the new value. Load settings once for the intended application lifetime, or design and test an explicit reload procedure. Updating a file alone is not a tested rotation procedure for an already running service.
These checks ran locally on Windows. They did not exercise Linux, Docker, a secrets manager, database connectivity, a live HTTP service, or a cloud deployment. Repeat the relevant checks in the deployment environment, including permissions and the actual process startup command.
Docker Compose environment variables determine what reaches a container process. Pydantic Settings then interprets the values available to Python. These are separate stages with separate precedence rules. If you supply files through Compose secrets, confirm their mounted names and paths match the application's settings configuration.
Once the startup behavior is predictable, use the API hosting guide to assess the operating model. Compute with Hivenet is an option for a CPU instance running your Python service or integration job. Your team supplies the configuration, controls secret access, and manages dependencies, processes, and monitoring. This example does not assume a managed secrets store or automatic credential rotation.
Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.