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 ?
In CustomerSchema you should pass the parameter as many=True, as you expect a list, such as: customers_schema = CustomerSchema(many=True)
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With