4

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

Shashank
  • 584
  • 5
  • 16
Sanjay
  • 1,958
  • 2
  • 17
  • 25

1 Answers1

3

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
Luis Orduz
  • 2,887
  • 1
  • 13
  • 19
  • Thanks for your help, now whenever I call 'foo.load(query_results)', it calls function from modelschema and ask for database session. is there any way to call load from Schema ? – Sanjay Nov 13 '17 at 10:49
  • Are you running this outside of a request? – Luis Orduz Nov 17 '17 at 21:55