Last modified: Mar 25, 2025 By Alexander Williams

How to Install Cerberus in Python Step by Step

Cerberus is a lightweight data validation library for Python. It helps validate dictionaries and nested structures. This guide will show you how to install it.

What Is Cerberus?

Cerberus validates data against a schema. It ensures data follows specific rules. This is useful for APIs, forms, and configurations.

Prerequisites

Before installing Cerberus, ensure you have Python installed. Check using python --version. If not, download it from python.org.

 
# Check Python version
python --version


Python 3.9.0

If you face issues like ModuleNotFoundError, refer to our guide on solving ModuleNotFoundError.

Install Cerberus Using pip

The easiest way to install Cerberus is via pip. Open your terminal or command prompt.

 
pip install cerberus


Successfully installed cerberus-1.3.4

This installs the latest version. Verify the installation with pip show cerberus.

Verify the Installation

After installing, verify Cerberus works. Create a Python script to test it.

 
from cerberus import Validator

schema = {'name': {'type': 'string'}}
data = {'name': 'John Doe'}

v = Validator(schema)
print(v.validate(data))  # True if valid


True

If the output is True, Cerberus is working correctly.

Basic Usage Example

Here’s a basic example of using Cerberus for validation.

 
from cerberus import Validator

# Define schema
schema = {
    'age': {'type': 'integer', 'min': 18},
    'email': {'type': 'string', 'regex': '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'}
}

# Data to validate
data = {'age': 25, 'email': 'test@example.com'}

v = Validator(schema)
print(v.validate(data))  # True
print(v.errors)  # Empty if valid


True
{}

This checks if age is an integer and email matches a regex pattern.

Handling Errors

Cerberus provides detailed error messages. This helps debug validation issues.

 
data = {'age': 'twenty', 'email': 'invalid-email'}
v = Validator(schema)
print(v.validate(data))  # False
print(v.errors)


False
{'age': ['must be of integer type'], 'email': ['value does not match regex']}

Errors show what went wrong. Fix the data accordingly.

Conclusion

Installing Cerberus in Python is simple with pip. It helps validate data structures efficiently. Follow this guide to get started.

For more Python tips, check our other tutorials. Happy coding!