pykwalify - JSON/YAML Schema Validator
pykwalify is a Python library and CLI tool for validating JSON and YAML data against a schema, based on the Kwalify schema specification. The current version is 1.8.0, with releases occurring periodically to add features, fix bugs, and update dependencies, though major development seems to have slowed since late 2020.
Warnings
- breaking Python 2.7 and 3.5 support has been dropped. pykwalify v1.8.0 and later require Python 3.6 or newer.
- breaking Support for the `PyYAML` parser has been completely removed in favor of `ruamel.yaml`. Attempts to use `PyYAML` will fail.
- gotcha `True` and `False` are no longer considered valid integers. This change affects schemas where boolean values might have previously passed integer validation.
- gotcha The default YAML parser was changed to `ruamel.yaml` from `PyYAML` (which was deprecated in 1.5.2 and removed in 1.8.0). Ensure `ruamel.yaml>=0.16.0` and `python-dateutil>=2.8.0` are installed to avoid dependency conflicts or parser issues.
Install
-
pip install pykwalify
Imports
- Core
from pykwalify.core import Core
- SchemaError
from pykwalify.errors import SchemaError
- ValidationError
from pykwalify.errors import ValidationError
Quickstart
import io
from pykwalify.core import Core, ValidationError
# Define your schema in YAML
schema_yaml = """
type: map
mapping:
name:
type: str
required: true
age:
type: int
range: {min: 0, max: 120}
required: false
"""
# Define your data in YAML
data_yaml = """
name: Alice
age: 30
"""
# Create Core instance with StringIO objects for schema and data
c = Core(source_data=io.StringIO(data_yaml), schema_data=io.StringIO(schema_yaml))
try:
c.validate()
print("Validation successful!")
except ValidationError as e:
print(f"Validation failed: {e}")
# Example of invalid data
invalid_data_yaml = """
name: Bob
age: 150
"""
c_invalid = Core(source_data=io.StringIO(invalid_data_yaml), schema_data=io.StringIO(schema_yaml))
try:
c_invalid.validate()
except ValidationError as e:
print(f"Invalid data validation failed as expected: {e}")