Skip to main content

python-marshmallow-validates-schema-decorator

#post

Validate the relationship between fields with Marshmallow’s @validates_schema decorator

When unverified data enters in your app, you can validate it by defining a Marshmallow schema like this:

from marshmallow import Schema, validates, validates_schema, fields, ValidationError
 
class UserSchema(Schema):
    email = fields.Str(required=True)
    age = fields.Integer(required=True)
 
    @validates("age")
    def validate_age(self, data, **kwargs):
        if data < 14:
            raise ValidationError("Too young!")
 
    @validates_schema
    def validate_email(self, data, **kwargs):
        if len(data["email"]) < 3:
            raise ValidationError("Email must be more than 3 characters", "email")
 
schema = NumberSchema()
try:
    schema.load({"field_a": 1, "field_b": 2})
except ValidationError as err:
    err.messages["_schema"]

Then, verify fields with complex requirements using @validates (docs):

 

And confirm important relationships between fields with @validates_schema (docs):1

 

You can include as many instances of @validates and @validates_schema as you like. Or just stuff everything in one big @validates_schema method. Your call.

Footnotes

  1. When using @validates_schema, it’s important to include **kwargs in your decorated method’s signature to avoid a TypeError saying <method name> got an unexpected keyword argument 'partial'. Per Marshmallow’s docs, partial and many are always passed as keyword arguments to the decorated method. ↩