Validating Python Data with Cerberus

In order to validate the data coming in, we require a schema to define the validation rules.Defining the SchemaUnderstanding precisely how our data should look is critical to defining a schema: without knowing what is considered to be valid data, it’s impossible to write the validation rules.Writing our schema using JSON, we will need to include specific key names that Cerberus will understand..Cerberus supports an abundance of keys to implement validation rules..Let’s begin by first declaring types for our Customer attributes with the type key.We’re off to a good start, but maybe we want to restrict the range of IDs that we’re prepared to accept?.Let’s impose bounds on the ID to be, say, between 0 and 100..Furthermore, let’s mark the ID as a required attribute, since every customer must have an ID..We can append these additional constraints to our schema using the min, max and required keys.The customer’s name requires similar restrictions..Since a string is an iterable type, where we can traverse it character-by-character, we apply length bounds using Cerberus’ minlength and maxlength properties.For Customer accounts, we’re working with a list of values, as opposed to an individual number or string..Therefore we need to add a little further configuration to this attribute’s schema..For both lists and dictionaries, Cerberus accepts a schema key.The schema key varies slightly between lists and dictionaries..For lists, this property should be treated precisely like constraining an individual attribute..For our customer accounts, we’ll accept a list of integers between 0 and 100.As for dictionaries, we should consider schema as a collection of its own key-value pairs..For customer contact details, we’ll want to store both a phone number and an email address.. More details

Leave a Reply