Sitemap

Member-only story

Validating Data with Cerberus

3 min readMar 3, 2024

--

Press enter or click to view image in full size
Photo by James Harrison on Unsplash

Introduction

Data validation is a critical aspect of software development, ensuring that input data meets specified criteria before processing. Python developers often rely on libraries to streamline data validation tasks, and one such versatile tool is Cerberus. In this tutorial, we’ll explore the Cerberus package and demonstrate its various uses and applications through practical examples.

What is Cerberus?

Cerberus is a lightweight and extensible Python library for data validation. It provides a simple and expressive syntax for defining validation rules and validating complex data structures such as dictionaries and JSON objects.

Example 1

Basic Data Validation Let’s start with a simple example to demonstrate how Cerberus can be used to validate basic data types:

from cerberus import Validator

schema = {'name': {'type': 'string', 'required': True},
'age': {'type': 'integer', 'required': True, 'min': 18}}

v = Validator(schema)

data = {'name': 'Alice', 'age': 25}

if v.validate(data):
print("Data is valid!")
else:
print("Data is invalid:", v.errors)

In this example, we define a schema with validation rules for the ‘name’ and ‘age’ fields. We then create a Validator instance and use it to…

--

--

Arun Rajendran
Arun Rajendran

Written by Arun Rajendran

Lead Machine Learning Engineer focused on NLP. I hope to write articles on Machine learning, travel, personal finance and investment.