Search code examples
pythonmarshmallow

Marshmallow serialization errors are empty even when validation fails


I'm adding marshmallow to my Python web service, mostly so that I can use the schemas to generate OpenAPI docs, but I'd also like the error checking on my API response serialization. I've read through the relevant documentation, but I don't understand why I don't see errors when I serialize incomplete objects.

For example, with the following schema:

class UserResponse(Schema):
    user = fields.Integer(required=True)
    email = fields.Email(required=True)
    name = fields.String(required=True)
    role = fields.String(required=True)

    class Meta:
        strict = True

schema = UserResponse()

Validation works as expected:

>>> schema.validate({'user': 1})
ValidationError: {'email': ['Missing data for required field.'], 'role': ['Missing data for required field.'], 'name': ['Missing data for required field.']}

But serialization returns an empty error list:

>>> schema.dump({'user':1})
MarshalResult(data={'user': 1}, errors={})

Is this how it's supposed to work? I'd expect an error to be returned if the serialized object is missing required fields.


Solution

  • By design, in marshmallow, validation is only performed on deserialization.

    See this issue.