Cerberus: Lightweight Schema Validator
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
- breaking Starting with Cerberus 1.3.0, the `allow_unknown` validator option (which controls whether unknown fields in a document are allowed) now defaults to `False`. Previously, it implicitly allowed unknown fields.
- gotcha Since Cerberus 1.1, `type` schema rules are processed *before* `coerce` rules. This means type validation is performed on the original value, not the coerced value.
- gotcha The `required: True` and `nullable: True` schema rules are orthogonal. `required: True` means the key *must* exist in the document. `nullable: True` means that if the key exists, its value *can* be `None`.
Install
-
pip install cerberus
Imports
- Validator
from cerberus import Validator
Quickstart
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}')