Introduction
Marshmallow is Python’s classic serialization library — convert complex objects (ORM models, dicts) to/from JSON, with validation. It predates Pydantic and is still widely used, especially in Flask apps. This post covers marshmallow from basics to production.
Setup
pip install marshmallow
Basic schema
from marshmallow import Schema, fields
class UserSchema(Schema):
id = fields.Int()
name = fields.Str(required=True)
email = fields.Email(required=True)
age = fields.Int(validate=lambda x: x >= 0)
created_at = fields.DateTime(dump_only=True) # only in output
schema = UserSchema()
# Deserialize (JSON → Python)
data = schema.loads('{"name": "Galvan", "email": "[email protected]", "age": 30}')
print(data) # {'name': 'Galvan', 'email': '[email protected]', 'age': 30}
# Serialize (Python → JSON)
user = {"id": 1, "name": "Galvan", "email": "[email protected]", "age": 30, "created_at": "2026-01-01"}
json_str = schema.dumps(user)
print(json_str) # {"id": 1, "name": "Galvan", ...}
Field types
from marshmallow import fields
class Schema(Schema):
# Primitives
name = fields.Str()
age = fields.Int()
score = fields.Float()
active = fields.Bool()
# Collections
tags = fields.List(fields.Str())
metadata = fields.Dict()
# Nested
address = fields.Nested(AddressSchema)
# Date/time
created_at = fields.DateTime()
birth_date = fields.Date()
login_time = fields.Time()
# Special
email = fields.Email()
url = fields.URL()
uuid = fields.UUID()
# Method (computed field)
full_name = fields.Method("get_full_name")
def get_full_name(self, obj):
return f"{obj['first']} {obj['last']}"
Validation
Built-in validators
from marshmallow import fields, validate
class UserSchema(Schema):
name = fields.Str(required=True, validate=validate.Length(min=1, max=100))
age = fields.Int(validate=validate.Range(min=0, max=150))
role = fields.Str(validate=validate.OneOf(["admin", "user", "mod"]))
website = fields.URL(allow_none=True)
Custom validators
from marshmallow import Schema, fields, validates, ValidationError
class UserSchema(Schema):
email = fields.Email(required=True)
password = fields.Str(required=True)
@validates("password")
def validate_password(self, value):
if len(value) < 8:
raise ValidationError("Password must be at least 8 characters")
if not any(c.isdigit() for c in value):
raise ValidationError("Password must contain a digit")
return value
Schema-level validation
from marshmallow import Schema, fields, validates_schema, ValidationError
class PasswordChange(Schema):
password = fields.Str(required=True)
confirm = fields.Str(required=True)
@validates_schema
def check_passwords(self, data, **kwargs):
if data["password"] != data["confirm"]:
raise ValidationError("Passwords do not match", field_name="confirm")
Partial updates
# Only validate provided fields
schema = UserSchema(partial=True)
data = schema.load({"name": "New Name"}) # age, email not required
Great for PATCH endpoints.
Excluding fields
schema = UserSchema(exclude=["password", "secret"])
# or
schema = UserSchema(only=["id", "name", "email"])
SQLAlchemy integration
pip install marshmallow-sqlalchemy
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
from models import User # SQLAlchemy model
class UserSchema(SQLAlchemyAutoSchema):
class Meta:
model = User
load_instance = True # deserialize to model instance
sqla_session = db_session
# Deserialize directly to a SQLAlchemy object
user = UserSchema().load({"name": "Galvan", "email": "[email protected]"})
db_session.add(user)
db_session.commit()
load_instance=True makes load() return a model instance instead of a dict — huge time-saver.
Flask integration
from flask import Flask, request, jsonify
from marshmallow import ValidationError
app = Flask(__name__)
schema = UserSchema()
@app.route("/users", methods=["POST"])
def create_user():
try:
data = schema.load(request.get_json())
except ValidationError as e:
return jsonify(e.messages), 400
# data is validated dict
user = create_user_in_db(data)
return schema.dump(user), 201
Marshmallow vs Pydantic
| Marshmallow | Pydantic | |
|---|---|---|
| Validation | On load() |
On construction |
| Serialization | dump() |
model_dump() |
| Type hints | No (field definitions) | Yes (native) |
| Performance | Slower | Faster (Rust core) |
| Ecosystem | Flask, SQLAlchemy | FastAPI, modern Python |
| Flexibility | More (custom fields, callbacks) | Less (opinionated) |
| Learning curve | Medium | Low |
Choose marshmallow for Flask apps, complex serialization, and when you need fine-grained control. Choose Pydantic for FastAPI, type safety, and performance.
Common mistakes
- Not using
partial=Truefor PATCH — PATCH sends partial data; withoutpartial=True, required fields fail. - Forgetting
load_instance=True— without it,load()returns a dict, not a model. - Validation in
__init__— marshmallow validates onload(), not construction. Don’t skip validation. - Not handling
ValidationError— always catch and return 400 withe.messages. - Mixing v2 and v3 — marshmallow 3.x is current. v2 is legacy. Check your version.
Key Concepts
- Schema = defines fields and validation
load()= deserialize + validate (JSON → Python)dump()= serialize (Python → JSON)@validates= custom field validation@validates_schema= cross-field validationpartial=True= allow partial data (PATCH)load_instance= return model instance, not dict
What to Try Next
- Add marshmallow to your Flask API.
- Migrate to Pydantic if using FastAPI.
- Use
marshmallow-sqlalchemyfor ORM integration. - Combine with type hints for full safety.
FAQ
Marshmallow vs Pydantic — which to use?
Pydantic for new projects (faster, type hints, FastAPI). Marshmallow for existing Flask apps or complex serialization needs. Both are valid; pick based on your framework.
Is marshmallow still maintained?
Yes — marshmallow 3.x is actively maintained. It’s not as trendy as Pydantic but remains widely used in the Flask ecosystem. It’s stable and reliable.
Can I use marshmallow with FastAPI?
You can, but it’s awkward (FastAPI expects Pydantic). Use Pydantic with FastAPI and marshmallow with Flask. Don’t mix.