Flask-Marshmallow is a thin integration layer for Flask (a Python web framework) and marshmallow (an object serialization/deserialization library) that adds additional features to marshmallow, including URL and Hyperlinks fields for HATEOAS-ready APIs. It also (optionally) integrates with Flask-SQLAlchemy.
pip install flask-marshmallow
Create your app.
from flask import Flask, jsonify
from flask_marshmallow import Marshmallow
app = Flask(__name__)
ma = Marshmallow(app)
Write your models.
from your_orm import Model, Column, Integer, String, DateTime
class User(Model):
email = Column(String)
password = Column(String)
date_created = Column(DateTime, auto_now_add=True)
Define your output format with marshmallow.
class UserSchema(ma.Schema):
class Meta:
# Fields to expose
fields = ('email', 'date_created', '_links')
# Smart hyperlinking
_links = ma.Hyperlinks({
'self': ma.URLFor('user_detail', id='<id>'),
'collection': ma.URLFor('users')
})
user_schema = UserSchema()
users_schema = UserSchema(many=True)
Output the data in your views.
@app.route('/api/users/')
def users():
all_users = User.all()
result = users_schema.dump(all_users)
return jsonify(result.data)
# OR
# return user_schema.jsonify(all_users)
@app.route('/api/users/<id>')
def user_detail(id):
user = User.get(id)
return user_schema.jsonify(user)
# {
# "email": "fred@queen.com",
# "date_created": "Fri, 25 Apr 2014 06:02:56 -0000",
# "_links": {
# "self": "/api/users/42",
# "collection": "/api/users/"
# }
# }
To learn more about marshmallow, check out its docs.
- Docs: https://flask-marshmallow.readthedocs.io/
- Changelog: http://flask-marshmallow.readthedocs.io/en/latest/changelog.html
- PyPI: https://pypi.python.org/pypi/flask-marshmallow
- Issues: https://github.com/marshmallow-code/flask-marshmallow/issues
MIT licensed. See the bundled LICENSE file for more details.