3
votes

Overview

I am using Flask-SqlAlchemy and now I am looking into marshmallow to help me serialize and deserialize request data.

I was able to successfully:

  1. Create my models using Flask-SqlAlchemy

  2. Use Flask-Marshmallow to serialize database objects using the same model, by using the Optional Flask-SqlAlchemy Integration

  3. Use marshmallow-jsonapi to quickly generate Json API compliant responses. This required me to declare new Schemas to specify which attributes I want to include (this is duplicate from Flask-SqlAlchemy Models)

Code Samples

Flask-SqlAlchemy Declarative Model

class Space(db.Model):

    __tablename__ = 'spaces'
    id = sql.Column(sql.Integer, primary_key=True)
    name = sql.Column(sql.String)
    version = sql.Column(sql.String)
    active = sql.Column(sql.Boolean)

flask_marshmallow Schema Declaration (Inherits from SqlAlchemy Model)

ma = flask_marshmallow.Marshmallow(app)

class SpaceSchema(ma.ModelSchema):
    class Meta:
        model = Space

# API Response
space = Space.query.first()
return SpaceSchema().dump(space).data

# Returns:
{
'id': 123,
'version': '0.1.0',
'name': 'SpaceName',
'active': True
}

marshmallow_json api - requires new Schema Declaration, must include each attribute and type manually

class SpaceJsonSchema(marshmallow_json.Schema):
    id = fields.Str(dump_only=True)
    name = fields.Str()
    version = fields.Str()
    active = fields.Bool()

    class Meta:
        type_ = 'spaces'
        self_url = '/spaces/{id}'
        self_url_kwargs = {'id': '<id>'}
        self_url_many = '/spaces/'
        strict = True

# Returns Json API Compliant
{
    'data': {
        'id': '1',
        'type': 'spaces',
        'attributes': {
            'name': 'Phonebooth',
            'active': True,
            'version': '0.1.0'
         },
        'links': {'self': '/spaces/1'}
    },
    'links': {'self': '/spaces/1'}
}

Issue

As shown in the code, marshmallow-jsonapi allows me to create json api compliant responses, but I end up having to maintain a Declarative Model + Schema Response model.

flask-marshmallow allows me to create Schema responses from the SqlAlchemy models, so I don't have to maintain a separate set of properties for each model.


Question

Is it at all possible to use flask-marshmallow and marshmallow-jsonapi together so 1. Create Marshmallow Schema from a SqlAlchemy model, AND automatically generate json api responses?

I tried creating Schema declaration that inherited from ma.ModelSchema and marshmallow_json.Schema, in both orders, but it does not work (raises exception for missing methods and properties)


marshmallow-jsonapi

marshmallow-jsonapi provides a simple way to produce JSON API-compliant data in any Python web framework.

flask-marshmallow

Flask-Marshmallow includes useful extras for integrating with Flask-SQLAlchemy and marshmallow-sqlalchemy.

1
looks like you can do some multiple inheritence in python i.e. class MyClass(Schema, SQLAlchemyAutoSchema): docs.sqlalchemy.org/en/13/orm/extensions/declarative/… i'm trying to get this to work now tooMoralCode
looks like someone else already did... stackoverflow.com/a/53035144MoralCode

1 Answers

0
votes

Not a solution to this exact problem but I ran into similar issues when implementing this library : https://github.com/thomaxxl/safrs (sqlalchemy + flask-restful + jsonapi compliant spec). I don't remember exactly how I got around it, but if you try it and serialization doesn't work I can help you resolve it if you open an issue in github