philiprehberger-env-validator
Schema-based environment variable validation with type coercion and helpful error messages.
Installation
pip install philiprehberger-env-validator
Usage
Basic Validation
from philiprehberger_env_validator import Schema, validate
schema = (
Schema()
.string("DATABASE_URL", description="PostgreSQL connection string")
.integer("PORT", default=3000)
.boolean("DEBUG", default=False)
.string("NODE_ENV", choices=["development", "staging", "production"])
)
config = validate(schema)
print(config["PORT"]) # 3000 (int, not string)
Field Types
schema = (
Schema()
.string("API_KEY")
.integer("MAX_CONNECTIONS")
.float_field("RATE_LIMIT")
.boolean("VERBOSE")
.url("WEBHOOK_URL")
.email("ADMIN_EMAIL")
)
Custom Validation
schema = Schema().string(
"API_KEY",
pattern=r"^sk-[a-zA-Z0-9]{32}$",
validator=lambda v: len(v) > 10,
)
Optional Fields
schema = (
Schema()
.string("REQUIRED_VAR")
.string("OPTIONAL_VAR", required=False, default="fallback")
)
Custom Source
config = validate(schema, source={"PORT": "8080", "DEBUG": "true"})
Error Handling
from philiprehberger_env_validator import ValidationError
try:
config = validate(schema)
except ValidationError as e:
for error in e.errors:
print(error)
Schema Documentation
Generate formatted help text documenting all fields, grouped by required and optional.
schema = (
Schema()
.url("DATABASE_URL", description="PostgreSQL connection string")
.string("API_KEY")
.boolean("DEBUG", default=False, required=False, description="Enable debug mode")
.integer("PORT", default=8000, required=False)
)
print(schema.generate_help())
# REQUIRED:
# DATABASE_URL (url): PostgreSQL connection string
# API_KEY (str): No description
#
# OPTIONAL:
# DEBUG (bool) [default: false]: Enable debug mode
# PORT (int) [default: 8000]: No description
Load from .env File
Read and validate a .env file directly against a schema.
schema = (
Schema()
.string("DATABASE_URL")
.integer("PORT", default=3000)
.boolean("DEBUG", default=False)
)
config = schema.load_from_env_file(".env")
print(config["DATABASE_URL"])
print(config["PORT"]) # coerced to int
The .env file uses standard KEY=VALUE format. Comments (#) and blank lines are skipped. Quoted values are unquoted automatically.
List Fields
list_field() parses comma-separated values into a list, with optional per-item type coercion.
schema = (
Schema()
.list_field("ALLOWED_HOSTS") # default: split on "," as strings
.list_field("PORTS", item_type=int) # coerce each element to int
.list_field("PATHS", sep=":") # custom separator
)
config = validate(schema, source={
"ALLOWED_HOSTS": "a.com, b.com, c.com",
"PORTS": "80,443,8080",
"PATHS": "/usr/bin:/usr/local/bin",
})
# {
# "ALLOWED_HOSTS": ["a.com", "b.com", "c.com"],
# "PORTS": [80, 443, 8080],
# "PATHS": ["/usr/bin", "/usr/local/bin"],
# }
JSON values
json_field() parses an env var value as JSON, returning the decoded object.
schema = (
Schema()
.json_field("FEATURE_FLAGS")
.json_field("LIMITS", required=False, default={"max": 100})
)
config = validate(schema, source={
"FEATURE_FLAGS": '{"beta": true, "experimental": false}',
})
# {
# "FEATURE_FLAGS": {"beta": True, "experimental": False},
# "LIMITS": {"max": 100},
# }
Invalid JSON raises ValidationError with a "cannot be converted to json" message.
Declarative schemas
Schema.from_dict() builds a schema from a plain dict — useful when the schema is loaded from YAML/JSON config rather than written in code.
schema = Schema.from_dict({
"PORT": {"type": "integer", "default": 8080},
"DEBUG": {"type": "boolean", "default": False},
"HOSTS": {"type": "list", "sep": ","},
"FEATURES": {"type": "json", "required": False, "default": {}},
})
config = validate(schema, source={"PORT": "3000", "DEBUG": "true", "HOSTS": "a,b"})
Supported type values: "string", "integer", "float", "boolean", "url", "email", "list", "json". Remaining keys are forwarded to the corresponding fluent method.
API
| Function / Class | Description |
|---|---|
validate(schema, source) |
Validate environment variables against a schema, returning typed dict |
Schema |
Fluent schema builder with string(), integer(), float_field(), boolean(), url(), email(), list_field() methods |
Schema.list_field(name, *, sep=",", item_type=str) |
Parse a comma-separated list with optional int/float coercion |
Schema.json_field(name, required=True, default=None) |
Parse the env var value as JSON via json.loads |
Schema.from_dict(spec) |
Build a Schema declaratively from a dict mapping field name to kwargs (with a "type" key) |
Schema.generate_help() |
Return formatted help text documenting all fields grouped by required/optional |
Schema.load_from_env_file(path) |
Load and validate a .env file against the schema |
FieldSpec |
Field specification with type, default, choices, pattern, validator, and description options |
ValidationError |
Raised when validation fails, contains list of error messages in errors |
Development
pip install -e .
python -m pytest tests/ -v
Support
If you find this project useful:
License
Metadata
Release files for philiprehberger-env-validator 0.4.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| philiprehberger_env_validator-0.4.0.tar.gz | 195.8 kB | Without provenance | Details for philiprehberger_env_validator-0.4.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| philiprehberger_env_validator-0.4.0-py3-none-any.whl | Python 3 | none | any | Details for philiprehberger_env_validator-0.4.0-py3-none-any.whl |
Total release size: 203.7 kB
Release files / philiprehberger_env_validator-0.4.0.tar.gz
| Download URL | philiprehberger_env_validator-0.4.0.tar.gz |
|---|---|
| Size | 195.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bc2427b2b1924d7b7bbcc1b8c5bec1db52302f6adfe73016883ed6e017da418b
|
|
BLAKE2b-256 checksum How to use checksums |
511e4c12253c562c8cdd430a42e5be01a855197c5ecce913ad0e01c539a2dd9c
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|
Release files / philiprehberger_env_validator-0.4.0-py3-none-any.whl
| Download URL | philiprehberger_env_validator-0.4.0-py3-none-any.whl |
|---|---|
| Size | 7.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
0dc49dc058805aae5041d4aff89767bee69659de031d77e1d276c9f7a89e8da5
|
|
BLAKE2b-256 checksum How to use checksums |
f3cad29403fbe192bba28006ffbd2e42c393ca846b7564abe3c4dbc04e028147
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.2.0 CPython/3.12.13
|
Security for philiprehberger-env-validator 0.4.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.