Marshmallow (Flask)
Marshmallow is a serialization and validation library used with Flask to convert between complex objects (like database models) and simple types (dicts/JSON). Schemas declare which fields to expose and how to validate incoming data.
Flask
APIs constantly translate between database objects and JSON. Marshmallow centralizes that translation in a Schema class: dumping turns a model into a JSON-ready dict, and loading parses and validates incoming JSON back into Python, raising errors on bad input.
A schema lists fields with types and options (required, validate ranges, dump_only for read-only fields like id). This keeps serialization logic out of your views and gives you consistent validation for free. The flask-marshmallow integration adds Flask-aware helpers, and marshmallow-sqlalchemy can auto-build schemas from models.
It complements jsonify rather than replacing it: you call schema.dump(obj) to get a dict, then return jsonify(that_dict), or use the schema's built-in jsonify helpers.
Syntax
class UserSchema(Schema):
id = fields.Int(dump_only=True)Examples
Python
from marshmallow import Schema, fields
class UserSchema(Schema):
id = fields.Int(dump_only=True)
name = fields.Str(required=True)
schema = UserSchema()
result = schema.dump(user_obj) # -> dict ready for jsonify