Marshmallow Nested Schema Validation

Validate deeply nested payloads with Marshmallow schemas, mapping field errors to their dotted paths and applying load-time defaults.

PythonForm Validation

Code

snippet
from marshmallow import Schema, ValidationError, fields, validate, validates


class AddressSchema(Schema):
    city = fields.Str(required=True, validate=validate.Length(min=2, max=60))
    countryCode = fields.Str(
        load_default='CN',
        validate=validate.Length(equal=2),
        data_key='country_code',
    )


class CustomerSchema(Schema):
    name = fields.Str(required=True, validate=validate.Length(min=1))
    email = fields.Email(required=True)
    tier = fields.Str(
        load_default='standard',
        validate=validate.OneOf(['standard', 'gold', 'platinum']),
    )
    address = fields.Nested(AddressSchema, required=True)

    @validates('email')
    def reject_blocklisted(self, value: str) -> None:
        if value.endswith('@example.test'):
            raise ValidationError('disposable domain is not allowed')


def validate_payload(raw: dict) -> dict:
    try:
        return CustomerSchema().load(raw)
    except ValidationError as exc:
        flat = {
            '.'.join(str(part) for part in path): messages[0]
            for path, messages in exc.messages_dict.items()
        }
        raise ValueError(flat) from exc


clean = validate_payload({
    'name': 'Ada',
    'email': '[email protected]',
    'address': {'city': 'Hangzhou'},
})
print('loaded with defaults:', clean['tier'], clean['address']['countryCode'])