Jeremy
Jeremy

Reputation: 2546

Flask Alchemy with Marshmallow returns empty JSON

I am trying to return a json data after query from my database using Flask Alchemy, and Flask Marshmallow

However, my code somehow always returns empty JSON data.

Here's my code :

My View :

@app.route('/customer/', methods=['GET'])
def get_customer():
  customers = models.Customer.query.all()
  #c = models.Customer.query.get(1) # Get Customer with an ID of 1

  customers_schema = CustomerSchema()

  print customers_schema.dump(customers).data
  payload = customers_schema.dump(customers).data
  resp = Response(response=payload, status=200, mimetype="application/json")
  return(resp)

My Models :

class Customer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    nickname = db.Column(db.String(64), index=True, unique=True)
    email = db.Column(db.String(120), index=True, unique=True)
    address = db.relationship('Address', backref='customer', lazy='dynamic')

    def __repr__(self):
        return '<Customer %r>' % (self.nickname)

My Schema :

class CustomerSchema(ma.ModelSchema):
    class Meta:
        model = Customer

This is the result as seen from the console :

 * Debugger is active!
 * Debugger pin code: 817-774-044
{}
127.0.0.1 - - [12/Nov/2016 09:37:59] "GET /customer/ HTTP/1.1" 200 -
{}
127.0.0.1 - - [12/Nov/2016 09:41:27] "GET /customer/ HTTP/1.1" 200 -

Is there anything that i miss ? Can anyone help ?

Upvotes: 7

Views: 4932

Answers (4)

Cactus
Cactus

Reputation: 924

Also, make sure that if you try to validate a database response from .query() is not an orm-mapped object and is rather converted to a dictionary, as described here: How to convert SQLAlchemy row object to a Python dict? in the row2dict code sample.

Upvotes: 0

Pierre Welmant
Pierre Welmant

Reputation: 78

I'd like to add something to the answers above.

In Marshmallow 3.x, the parameter strict has been removed as schemas are always strict.

An empty JSON object as result may be caused by different cases, for instance I have once mistaken "=" with ":" in the schema which results in a [ Unknown field. ] on dumps and an empty JSON Object as result.

In order to debug in Marshmallow 3.x you may use Schema.validate which returns a dictionary of validation errors :

  customers_schema = CustomerSchema()

  print(customers_schema.validate(customers))

I hope this may help some people in the future

Upvotes: 6

user7801624
user7801624

Reputation: 81

In CustomerSchema you should pass the parameter as many=True, as you expect a list, such as: customers_schema = CustomerSchema(many=True)

Upvotes: 8

Maxim Kulkin
Maxim Kulkin

Reputation: 2788

You are probably hitting some error during serialization and you just ignore it. Try instantiating you schema with strict=True to see what errors are there:

customers_schema = CustomerSchema(strict=True)

Upvotes: 1

Related Questions