Skip to main content

The most comprehensive, production-ready environment variable validation library for Python

Project description

๐Ÿš€ env-validator

The most comprehensive, production-ready environment variable validation library for Python

PyPI version Python 3.8+ License: MIT Code style: black Tests Documentation

The definitive solution for Python environment variable validation that developers choose because it's genuinely the best tool available.

๐ŸŒŸ Why env-validator?

env-validator is the most comprehensive, feature-rich environment variable validation library for Python. Built with production-ready features, security-first design, and exceptional developer experience, it's the tool that will revolutionize how you manage environment variables.

โœจ Key Features

  • ๐Ÿ”’ Advanced Security: Secret scanning, compliance validation, encryption key verification
  • ๐Ÿš€ Framework Integration: Seamless Django, Flask, FastAPI support
  • ๐Ÿ“Š Monitoring & Observability: Health checks, drift detection, performance metrics
  • ๐Ÿ› ๏ธ Developer Tools: CLI, interactive setup, codebase scanning
  • ๐Ÿ—๏ธ Team Collaboration: Shared templates, audit logging, change notifications
  • ๐Ÿ”ง Extensible Architecture: Plugin system, custom validators, middleware support
  • ๐Ÿ“ฑ Cross-Platform: Windows, macOS, Linux support
  • ๐ŸŽฏ Zero Configuration: Works out of the box with sensible defaults

๐Ÿš€ Quick Start

Installation

pip install env-validator

Basic Usage

from env_validator import EnvironmentValidator, ValidationError

# Define your environment schema
validator = EnvironmentValidator({
    "DATABASE_URL": {
        "type": "str",
        "required": True,
        "validators": ["database_url"]
    },
    "API_KEY": {
        "type": "str", 
        "required": True,
        "validators": ["api_key"],
        "sensitive": True
    },
    "DEBUG": {
        "type": "bool",
        "default": False
    },
    "PORT": {
        "type": "int",
        "default": 8000,
        "validators": ["port_range"]
    }
})

# Validate your environment
try:
    config = validator.validate()
    print(f"โœ… Environment validated successfully!")
    print(f"Database: {config.DATABASE_URL}")
    print(f"Debug mode: {config.DEBUG}")
except ValidationError as e:
    print(f"โŒ Environment validation failed: {e}")

Framework Integration

Django

# settings.py
from env_validator import DjangoEnvironmentValidator

env = DjangoEnvironmentValidator({
    "SECRET_KEY": {"type": "str", "required": True, "validators": ["secret_key"]},
    "DATABASE_URL": {"type": "str", "required": True, "validators": ["database_url"]},
    "DEBUG": {"type": "bool", "default": False},
    "ALLOWED_HOSTS": {"type": "list", "default": ["localhost"]},
})

# Validate and load environment
config = env.validate()

SECRET_KEY = config.SECRET_KEY
DATABASES = {
    'default': env.parse_database_url(config.DATABASE_URL)
}
DEBUG = config.DEBUG
ALLOWED_HOSTS = config.ALLOWED_HOSTS

FastAPI

# config.py
from env_validator import FastAPIEnvironmentValidator
from pydantic import BaseSettings

class Settings(BaseSettings):
    env_validator = FastAPIEnvironmentValidator({
        "DATABASE_URL": {"type": "str", "required": True},
        "API_KEY": {"type": "str", "required": True, "sensitive": True},
        "ENVIRONMENT": {"type": "str", "default": "development"},
    })
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.env_validator.validate()

settings = Settings()

๐Ÿ› ๏ธ CLI Tools

Environment Validation

# Validate current environment
env-validator validate

# Validate with custom schema file
env-validator validate --schema schema.yaml

# Generate environment report
env-validator report --output html

Interactive Setup

# Interactive environment setup wizard
env-validator setup

# Generate configuration templates
env-validator template --framework django

Security Scanning

# Scan for secrets and sensitive data
env-validator scan --secrets

# Compliance check
env-validator scan --compliance gdpr

๐Ÿ”ง Advanced Features

Custom Validators

from env_validator import BaseValidator, ValidationError

class CustomAPIValidator(BaseValidator):
    def validate(self, value: str) -> str:
        if not value.startswith("api_"):
            raise ValidationError("API key must start with 'api_'")
        return value

validator = EnvironmentValidator({
    "API_KEY": {
        "type": "str",
        "validators": [CustomAPIValidator()]
    }
})

Environment-Specific Configurations

validator = EnvironmentValidator({
    "DATABASE_URL": {
        "type": "str",
        "required": True,
        "environments": {
            "development": "sqlite:///dev.db",
            "staging": {"type": "str", "validators": ["database_url"]},
            "production": {"type": "str", "validators": ["database_url", "ssl_required"]}
        }
    }
})

Monitoring Integration

from env_validator import MonitoringValidator

# Health check endpoint
@app.get("/health/env")
async def environment_health():
    return MonitoringValidator.health_check()

# Metrics endpoint
@app.get("/metrics/env")
async def environment_metrics():
    return MonitoringValidator.get_metrics()

๐Ÿ“Š Built-in Validators

Security Validators

  • secret_key: Validates secret key strength and entropy
  • api_key: Validates API key format and security
  • encryption_key: Validates encryption key requirements
  • password_strength: Checks password complexity requirements

Network Validators

  • url: Validates URL format and accessibility
  • ip_address: Validates IPv4/IPv6 addresses
  • port_range: Validates port numbers
  • database_url: Validates database connection strings

Data Validators

  • email: RFC-compliant email validation
  • json: JSON format validation
  • file_path: File path existence and permissions
  • directory_path: Directory existence and permissions

Cloud Validators

  • aws_arn: AWS ARN format validation
  • gcp_project_id: Google Cloud project ID validation
  • azure_resource_id: Azure resource identifier validation

๐Ÿ”’ Security Features

Secret Detection

validator = EnvironmentValidator({
    "API_KEY": {
        "type": "str",
        "sensitive": True,
        "validators": ["secret_scanning"]
    }
})

# Automatically detects and protects sensitive values
config = validator.validate()
print(config.API_KEY)  # Shows: "***REDACTED***"

Compliance Validation

validator = EnvironmentValidator({
    "PII_DATA": {
        "type": "str",
        "compliance": ["gdpr", "hipaa"],
        "encryption": "required"
    }
})

๐Ÿ“ˆ Monitoring & Observability

Health Checks

from env_validator import HealthChecker

# Check environment health
health = HealthChecker.check()
if not health.is_healthy:
    print(f"Environment issues: {health.issues}")

Drift Detection

from env_validator import DriftDetector

# Detect configuration drift
drift = DriftDetector.detect()
if drift.has_changes:
    print(f"Configuration drift detected: {drift.changes}")

๐Ÿ—๏ธ Framework Integrations

Django

# settings.py
from env_validator.django import DjangoEnvironmentValidator

env = DjangoEnvironmentValidator.from_settings_file()
config = env.validate()

# Automatic Django settings integration
SECRET_KEY = config.SECRET_KEY
DATABASES = config.DATABASES

Flask

# app.py
from env_validator.flask import FlaskEnvironmentValidator

app = Flask(__name__)
env = FlaskEnvironmentValidator(app, {
    "SECRET_KEY": {"type": "str", "required": True},
    "DATABASE_URL": {"type": "str", "required": True},
})

FastAPI

# main.py
from env_validator.fastapi import FastAPIEnvironmentValidator

app = FastAPI()
env = FastAPIEnvironmentValidator(app, {
    "API_KEY": {"type": "str", "required": True},
    "DATABASE_URL": {"type": "str", "required": True},
})

๐Ÿš€ Performance Features

  • Lazy Loading: Validators load only when needed
  • Caching: Repeated validations are cached
  • Async Support: Non-blocking validation operations
  • Memory Efficient: Minimal memory footprint

๐Ÿ“š Documentation

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

git clone https://github.com/Sherin-SEF-AI/env-validator.git
cd env-validator
pip install -e ".[dev]"
pre-commit install
pytest

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Built with โค๏ธ by the Python community
  • Inspired by the need for better environment variable management
  • Thanks to all contributors and users

๐Ÿ“Š Project Status

  • โœ… Core validation engine
  • โœ… Advanced validators library
  • โœ… Framework integrations
  • โœ… CLI tools
  • โœ… Security features
  • โœ… Monitoring & observability
  • โœ… Documentation
  • โœ… Testing suite
  • ๐Ÿšง Community features
  • ๐Ÿšง Performance optimizations

Made with โค๏ธ by Sherin Joseph Roy

GitHub | Documentation | Issues | Discussions

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

envvar_validator-1.0.0.tar.gz (43.2 kB view details)

Uploaded Source

Built Distribution

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

envvar_validator-1.0.0-py3-none-any.whl (46.0 kB view details)

Uploaded Python 3

File details

Details for the file envvar_validator-1.0.0.tar.gz.

File metadata

  • Download URL: envvar_validator-1.0.0.tar.gz
  • Upload date:
  • Size: 43.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.3

File hashes

Hashes for envvar_validator-1.0.0.tar.gz
Algorithm Hash digest
SHA256 fb5d1212ee3bd8501d6f0bca1ac9f50673a5b32b2ba9840c28b32bfe0981eb23
MD5 df3aec71d4d2a07be0cb5742b55de773
BLAKE2b-256 b642df4f616d2a481544768f49d829e7a685c913df61cfc0423d067fd6bcae2e

See more details on using hashes here.

File details

Details for the file envvar_validator-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for envvar_validator-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 34ac33431fa4ff5a6640bb16fc585e0399983c4089615f9ddd61cbfe3ee48f0c
MD5 7adbee9988147338ff0506895cf564a5
BLAKE2b-256 fc5cde8d508c460b8f04f26fde3239689adea9aec9c38a659ab9fb0804dffffd

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