Skip to main content

Schema-based environment variable validation with type coercion and helpful error messages.

Project description

philiprehberger-env-validator

Tests PyPI version Last updated

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"],
# }

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.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:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

philiprehberger_env_validator-0.3.0.tar.gz (8.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

philiprehberger_env_validator-0.3.0-py3-none-any.whl (6.8 kB view details)

Uploaded Python 3

File details

Details for the file philiprehberger_env_validator-0.3.0.tar.gz.

File metadata

File hashes

Hashes for philiprehberger_env_validator-0.3.0.tar.gz
Algorithm Hash digest
SHA256 e2cf6f9fe6d84041e7272a115cbd6f4e0508dfc087d2510aed6a65dbafc2b04b
MD5 0b960984f71f223a2c7d5cfc23fff241
BLAKE2b-256 208a6202b155eb202818078394aee10bd9d07bdf1f9d1beed5f0d0bce3965ddb

See more details on using hashes here.

File details

Details for the file philiprehberger_env_validator-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for philiprehberger_env_validator-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5768fdcc948e9d550c6460777e162d0439d05516b7379bef9c160fd391268a38
MD5 a95eb20c81bcdb4cd6b866a0f549b7d9
BLAKE2b-256 74b20de5c85545b8ef41cab990d16cbb3a03bdd955c4897f87db6748884a685a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page