Take JSONAPI schema from model

Viewed 425

In my Rest application I want to return json like JSONAPI format, but I need to create Schema class for it and create every field again that are already there in my model. So instead of creating every field in schema class can I not take it from DB Model.. below is my model class

class Author(db.Model):
  id = db.Column(db.Integer)
  name = db.Column(db.String(255))

I am defining Schema like below.

class AuthorSchema(Schema):
    id = fields.Str(dump_only=True)
    name = fields.Str()
    metadata = fields.Meta()

    class Meta:
        type_ = 'people'
        strict = True

So here, id and name I have defined it twice. so is there any option in marshmallow-jsonapi to assign model name in schema class so it can take all fields from model
Note: I am using marshmallow-jsonapifor it, I have tried marshmallow-sqlalchemy , it has that option but it not return json in JSONAPI format

1 Answers

You can use flask-marshmallow's ModelSchema and marshmallow-sqlalchemy in combination with marshmallow-jsonapi with the caveat that you have to subclass not only the Schema classes but also the SchemaOpts classes, like this:

# ...
from flask_marshmallow import Marshmallow
from marshmallow_jsonapi import Schema, SchemaOpts
from marshmallow_sqlalchemy import ModelSchemaOpts


# ...

ma = Marshmallow(app)

# ...

class JSONAPIModelSchemaOpts(ModelSchemaOpts, SchemaOpts):
    pass


class AuthorSchema(ma.ModelSchema, Schema):
    OPTIONS_CLASS = JSONAPIModelSchemaOpts

    class Meta:
        type_ = 'people'
        strict = True
        model = Author

# ...
foo = AuthorSchema()
bar = foo.dump(query_results).data # This will be in JSONAPI format including every field in the model
Related