Registry / serialization / flask-marshmallow

flask-marshmallow

JSON →
library1.5.0pypypi✓ verified 24d ago

Flask-Marshmallow is a thin integration layer for Flask, a Python web framework, and Marshmallow, an object serialization/deserialization library. It enhances Marshmallow with features like URL and Hyperlinks fields for HATEOAS-ready APIs and offers optional integration with Flask-SQLAlchemy. The current version is 1.4.0, and it follows a release cadence tied to Flask and Marshmallow updates.

pip install flask-marshmallow
INSTALL
IMPORT
SIG · FLASK-MARSHMALLOW
F
flask-marshmallow
serializationpythonv1.5.0
Install
2.5s avg
Import
953ms
Disk
22MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.5.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.976s · 23.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.5s · import 0.930s · 24MB
22MB installed
● package 22MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Marshmallow
from flask_marshmallow import Marshmallow
SQLAlchemyAutoSchema
from flask_marshmallow.sqla import SQLAlchemyAutoSchema
from flask_marshmallow import ModelSchema
ModelSchema and TableSchema were removed in v0.12.0; use SQLAlchemyAutoSchema or SQLAlchemySchema instead.

This quickstart initializes a Flask app and Flask-Marshmallow, defines a simple User class and a corresponding UserSchema. It then demonstrates how to use the schema to serialize single and multiple User objects through Flask routes, including hyperlinking.

from flask import Flask from flask_marshmallow import Marshmallow app = Flask(__name__) ma = Marshmallow(app) class User: def __init__(self, id, name, email): self.id = id self.name = name self.email = email @classmethod def get(cls, id): # Simulate fetching a user from a DB if id == 1: return cls(1, 'Alice', 'alice@example.com') return None @classmethod def all(cls): # Simulate fetching all users return [cls(1, 'Alice', 'alice@example.com'), cls(2, 'Bob', 'bob@example.com')] class UserSchema(ma.Schema): id = ma.Int(dump_only=True) name = ma.Str(required=True) email = ma.Email(required=True) _links = ma.Hyperlinks({ "self": ma.URLFor("user_detail", values=dict(id="<id>")), "collection": ma.URLFor("users") }) user_schema = UserSchema() users_schema = UserSchema(many=True) @app.route("/api/users/") def users(): all_users = User.all() return users_schema.dump(all_users) @app.route("/api/users/<int:id>") def user_detail(id): user = User.get(id) if user: return user_schema.dump(user) return {"message": "User not found"}, 404 if __name__ == "__main__": with app.test_request_context(): # Example usage in a test context print(users()) print(user_detail(1)) print(user_detail(99))
Debug
Known issues
breakingThe `ModelSchema` and `TableSchema` classes were removed in `flask-marshmallow` v0.12.0. You must migrate to `SQLAlchemySchema` or `SQLAlchemyAutoSchema`.
fix
Replace `ma.ModelSchema` or `ma.TableSchema` with `ma.SQLAlchemyAutoSchema` (recommended) or `ma.SQLAlchemySchema`. Ensure `marshmallow-sqlalchemy` is installed if using these. For example, `class AuthorSchema(ma.SQLAlchemyAutoSchema): class Meta: model = Author`.
affects: >=0.12.0
breakingThe syntax for defining `Hyperlinks` fields changed in `flask-marshmallow` v0.14.0. The `id="<id>"` argument is no longer supported; `values=dict(id="<id>")` should be used instead.
fix
Update `ma.URLFor` calls within `ma.Hyperlinks` to use the `values` dictionary. Example: `ma.URLFor("user_detail", values=dict(id="<id>"))`.
affects: >=0.14.0
gotchaWhen integrating with Flask-SQLAlchemy, the `SQLAlchemy` extension must be initialized before the `Marshmallow` extension.
fix
Ensure `db = SQLAlchemy(app)` is called before `ma = Marshmallow(app)` in your application setup.
affects: *
gotchaFlask's `jsonify` method sorts keys by default, which can override `ordered=True` in your Marshmallow schemas. This can lead to unexpected key ordering in your JSON responses.
fix
To disable Flask's default key sorting, set `app.config['JSON_SORT_KEYS'] = False` in your Flask application configuration. In production, consider letting `jsonify` sort keys for cacheability.
affects: *
deprecatedAccessing `flask_marshmallow.__version__` and `flask_marshmallow.__version_info__` attributes is deprecated.
fix
Use feature detection or `importlib.metadata.version("flask-marshmallow")` to get the package version.
affects: Post 1.x (exact version for removal not specified, but good to be aware)
gotchaMarshmallow 3.x (a dependency of flask-marshmallow) removed implicit field creation. Schemas no longer infer fields automatically from data introspection.
fix
For automatic field generation from ORM models, explicitly use `marshmallow-sqlalchemy`'s `SQLAlchemyAutoSchema`. Otherwise, define all fields explicitly in your `ma.Schema` classes.
affects: Flask-Marshmallow versions requiring Marshmallow 3.x
Errors
Common errors & fixes
NameError: name 'ma' is not defined
This error typically occurs when the `Marshmallow` instance (often named `ma`) is not imported or initialized correctly in the file where the schema is defined, or if there's a circular import issue preventing its proper initialization within the Flask application context.
fix
Ensure the `Marshmallow` instance is initialized with your Flask app (e.g., `ma = Marshmallow(app)`) and then properly imported into any module where schemas are defined. For complex applications, consider initializing extensions in a dedicated `extensions.py` file and importing them.
AttributeError: 'Marshmallow' object has no attribute 'ModelSchema'
This error usually indicates a version incompatibility, specifically when using an older `Marshmallow-SQLAlchemy` syntax (`ma.ModelSchema`) with a newer version of `Marshmallow` or `Marshmallow-SQLAlchemy` where `ModelSchema` has been deprecated or moved.
fix
Replace `ma.ModelSchema` with `ma.SQLAlchemyAutoSchema` or `SQLAlchemySchema` (imported from `marshmallow_sqlalchemy`) in your schema definitions.
ImportError: cannot import name 'Marshmallow' from 'flask_marshmallow'
This error suggests that the `flask-marshmallow` library is either not installed, installed in a different Python environment, or there's a version conflict.
fix
Verify `flask-marshmallow` is installed in the correct virtual environment using `pip show flask-marshmallow`. If not, install it via `pip install flask-marshmallow`. If using an IDE, ensure the correct Python interpreter for your virtual environment is selected.
TypeError: __init__() got an unexpected keyword argument 'strict'
The `strict` keyword argument was removed in Marshmallow 3.x. Using it with `flask-marshmallow` (which relies on Marshmallow) when Marshmallow 3.x or later is installed will raise this error.
fix
Remove the `strict=True` argument from your schema instantiation. Marshmallow 3.x handles strictness differently, typically by default or through other configuration options.
AttributeError: type object 'YourSchemaName' has no attribute 'TYPE_MAPPING'
This error occurs when trying to serialize a SQLAlchemy model with `flask-marshmallow` using `ma.ModelSchema` (or a similar auto-generated schema) in an older version of `marshmallow-sqlalchemy` or when the schema definition is incorrect, particularly in how it links to the SQLAlchemy model.
fix
Ensure your schema correctly inherits from `ma.SQLAlchemyAutoSchema` and that the `Meta` class explicitly defines the `model` attribute pointing to your SQLAlchemy model. Also, check for updated syntax in `marshmallow-sqlalchemy` documentation if you are on an older version.
Upgrade
Version history
1.5.0latest on PyPI · released Apr 16, 2026
Audit
Dependencies
flaskrequiredCore web framework integration.
marshmallowrequiredCore serialization/deserialization library.
flask-sqlalchemyoptionalOptional integration for SQLAlchemy ORM.
marshmallow-sqlalchemyoptionalOptional integration for SQLAlchemy ORM schema generation.
Agent activity
7 hits · last 30 days
node
6
Resources