Tech With Galvan
Back to Articles
TechMay 16, 2027 • 4 min read

Python Cerberus: Lightweight Data Validation

Cerberus for Python — lightweight, schema-based data validation. When to use Cerberus vs Pydantic vs marshmallow.

Galvan
Galvan

Founder & Creator

Introduction

Cerberus is a lightweight, schema-based data validation library for Python. Unlike Pydantic (type hints) or marshmallow (serialization), Cerberus focuses purely on validation — is this data shape correct? It’s simpler, more flexible, and great for validating config files, API payloads, and user input.

Setup

pip install cerberus

Basic validation

from cerberus import Validator

schema = {
    "name": {"type": "string", "required": True, "minlength": 1},
    "age": {"type": "integer", "min": 0, "max": 150},
    "email": {"type": "string", "regex": r"^[^\s@]+@[^\s@]+\.[^\s@]+$"},
}

v = Validator(schema)

doc = {"name": "Galvan", "age": 30, "email": "[email protected]"}
print(v.validate(doc))   # True

doc = {"name": "", "age": 200, "email": "bad"}
print(v.validate(doc))   # False
print(v.errors)          # {'name': ['min length is 1'], 'age': ['max value is 150'], 'email': ['...']}

Schema types

schema = {
    "name": {"type": "string"},
    "age": {"type": "integer"},
    "score": {"type": "float"},
    "active": {"type": "boolean"},
    "tags": {"type": "list"},
    "metadata": {"type": "dict"},
    "created_at": {"type": "datetime"},
    "id": {"type": "integer", "coerce": int},   # coerce string → int
}

Constraints

schema = {
    # Strings
    "name": {"type": "string", "minlength": 1, "maxlength": 100},
    "code": {"type": "string", "regex": r"^[A-Z]{3}\d{3}$"},

    # Numbers
    "age": {"type": "integer", "min": 0, "max": 150},
    "price": {"type": "float", "min": 0.0},

    # Collections
    "tags": {"type": "list", "minlength": 1, "maxlength": 10},
    "scores": {"type": "list", "schema": {"type": "integer", "min": 0, "max": 100}},

    # Required/optional
    "id": {"type": "integer", "required": True},
    "nickname": {"type": "string", "nullable": True},

    # Allowed values
    "role": {"type": "string", "allowed": ["admin", "user", "mod"]},

    # Defaults
    "active": {"type": "boolean", "default": True},
}

Nested validation

schema = {
    "user": {
        "type": "dict",
        "schema": {
            "name": {"type": "string", "required": True},
            "email": {"type": "string", "required": True},
        },
    },
    "items": {
        "type": "list",
        "schema": {
            "type": "dict",
            "schema": {
                "product": {"type": "string", "required": True},
                "qty": {"type": "integer", "min": 1},
            },
        },
    },
}

doc = {
    "user": {"name": "Galvan", "email": "[email protected]"},
    "items": [{"product": "Widget", "qty": 2}, {"product": "Gadget", "qty": 1}],
}
v.validate(doc)   # True

Custom validators

def check_unique_username(field, value, error):
    if value in existing_users:
        error(field, "username already taken")

schema = {
    "username": {"type": "string", "check_with": check_unique_username},
}

Or use validator decorator:

from cerberus import Validator

class MyValidator(Validator):
    def _validate_is_even(self, is_even, field, value):
        if is_even and value % 2 != 0:
            self._error(field, "must be even")

schema = {"number": {"type": "integer", "is_even": True}}
v = MyValidator(schema)
v.validate({"number": 4})   # True
v.validate({"number": 3})   # False

Normalization (coercion)

schema = {
    "age": {"type": "integer", "coerce": int},
    "tags": {"type": "list", "coerce": lambda v: v.split(",") if isinstance(v, str) else v},
}

v = Validator(schema, normalize=True)
doc = {"age": "30", "tags": "python,ai,web"}
v.normalized(doc)
# {"age": 30, "tags": ["python", "ai", "web"]}

Cerberus can coerce/normalize data during validation.

Purging unknown fields

schema = {"name": {"type": "string"}}
v = Validator(schema, purge_unknown=True)
doc = {"name": "Galvan", "extra": "field", "junk": 42}
v.normalized(doc)   # {"name": "Galvan"} — unknowns removed

Great for sanitizing API payloads.

Cerberus vs Pydantic vs marshmallow

Cerberus Pydantic Marshmallow
Validation Schema-based Type hints Schema-based
Serialization No Yes Yes
Performance Fast Fastest (Rust) Slower
Flexibility High (custom rules) Medium High
Type safety No Yes No
Learning curve Low Low Medium
Best for Config, payloads, simple validation APIs, models, FastAPI Flask, complex serialization

Choose Cerberus for lightweight validation (config files, simple payloads). Pydantic for type-safe models and FastAPI. Marshmallow for Flask serialization.

Common mistakes

  • Not validating at boundaries — validate all external input (API payloads, config files, user input).
  • Trusting client data — always validate server-side, even if the frontend validates.
  • Overly strict schemas — allow extra fields with purge_unknown instead of rejecting everything.
  • Not using coerce — user input is often strings; coerce to the right type.
  • Ignoring v.errors — always check and return errors to the user.

Key Concepts

  • Validator = validates data against a schema
  • Schema = dict defining field types and constraints
  • validate() = returns True/False, populates v.errors
  • normalized() = validate + coerce + purge
  • check_with = custom validation function
  • coerce = type conversion during validation

What to Try Next

FAQ

Cerberus vs Pydantic — which to use?

Cerberus = lightweight, schema-based, no serialization. Pydantic = type hints, serialization, FastAPI integration. Use Cerberus for simple validation; Pydantic for models and APIs.

Is Cerberus still maintained?

Yes — Cerberus 1.3.x is stable and maintained. It’s not as trendy as Pydantic but remains a solid choice for lightweight validation.

Can Cerberus handle nested data?

Yes — use schema for nested dicts and lists. See the nested validation example above. Deeply nested structures can get verbose; for complex nesting, Pydantic’s nested models are cleaner.