Marshmallow Nested Schema Validation
Validate deeply nested payloads with Marshmallow schemas, mapping field errors to their dotted paths and applying load-time defaults.
Code
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': 'ada@example.com',
'address': {'city': 'Hangzhou'},
})
print('loaded with defaults:', clean['tier'], clean['address']['countryCode'])Inside the snippet
Count the classes AddressSchema and CustomerSchema and the functions reject_blocklisted and validate_payload as the entire surface area of Marshmallow Nested Schema Validation.
Iteration happens inside for path, messages in exc.messages_dict.items() — everything outside it runs once. Everything borrowed from marshmallow is visible in one line: Schema, ValidationError, fields, validate, validates. A ValidationError and ValueError is raised inside an except block, so it is conditional on that failure being handled in the first place.
Points of care
- Plan for an install step:
marshmallowis a real dependency, resolved by the package manager. - The guard
value.endswith('@example.test')short-circuits the flow with an earlyraisewhen its condition holds.
Putting it to use
The primary signature is def reject_blocklisted(self, value: str) -> None
Output lines are prefixed (loaded with defaults:), making each step’s effect easy to spot.
Callers only need reject_blocklisted — everything else stays internal.
Core lines
def reject_blocklisted(self, value: str) -> None:
if value.endswith('@example.test'):
raise ValidationError('disposable domain is not allowed')
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()
}
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
Interactive Tools for This Topic
FAQ
- When is the exception raised?
- Inside an `except` handler — the `ValidationError` and `ValueError` fires only while that failure type is already being handled, not on its own trigger.
- Does this require external packages?
- Yes — `marshmallow`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.