Flask-Marshmallow

1.4.0 · active · verified Sat Apr 11

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.

Warnings

Install

Imports

Quickstart

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))

view raw JSON →