User Serialization with Marshmallow and Validation

  • Share this:

Code introduction


This function uses the Marshmallow library to serialize a user object into JSON format. If the user object does not meet the Schema definition requirements, it will return error information.


Technology Stack : Marshmallow

Code Type : Serialize

Code Difficulty : Intermediate


                
                    
def serialize_user(user):
    from marshmallow import Schema, fields, ValidationError
    class UserSchema(Schema):
        id = fields.Int(required=True)
        username = fields.Str(required=True)
        email = fields.Email(required=True)
        age = fields.Int(required=True)
    
    try:
        data = UserSchema().dump(user)
        return data
    except ValidationError as err:
        return err.messages                
              
Tags: