Cerberus: Lightweight Schema Validator

1.3.8 · active · verified Thu Apr 09

Cerberus is a lightweight, extensible data validation library for Python dictionaries. It allows you to define a schema and then validate whether a given dictionary conforms to that schema, supporting various data types, constraints, and custom validation rules. The current version is 1.3.8, and it maintains a stable release cadence with incremental updates within the 1.x series.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a schema with various rules (type, length, required, regex, min/max, nullable). It then creates a Validator instance, validates a sample document, and prints success or error messages. It also includes an example of an invalid document to show error reporting.

from cerberus import Validator

schema = {
    'name': {'type': 'string', 'minlength': 3, 'maxlength': 10, 'required': True},
    'age': {'type': 'integer', 'min': 0, 'max': 99, 'nullable': True},
    'email': {'type': 'string', 'regex': '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'}
}

document = {
    'name': 'John Doe',
    'age': 30,
    'email': 'john.doe@example.com'
}

v = Validator(schema)

if v.validate(document):
    print('Document is valid.')
    print(f'Normalized document: {v.normalized(document)}')
else:
    print('Document is invalid.')
    print(f'Errors: {v.errors}')

# Example with an invalid document
invalid_document = {
    'name': 'Jo',
    'age': 150,
    'city': 'New York' # Unknown field
}

if not v.validate(invalid_document):
    print(f'Invalid document errors: {v.errors}')

view raw JSON →