19421608 19421608 - 2 months ago 25
Python Question

Issue with Flask-Marshmallow exposing DB contents via API

I am developing a API which will return entries from a Database. I am using Flask-SQLAlchemy, Flask-Marshmallow, Flask-Admin and Docker to package it all up.

In one file Packages.py I have the following code regarding the database. The class PckagesSchema is the class I've added when trying to get Flash-Marshmallow working.

class Packages(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
trackingnumber = db.Column(db.String(15))
email = db.Column(db.String(80))
localid = db.Column(db.String(80))

class PackagesSchema(ma.ModelSchema):
class Meta:
model = Packages


The in the main file I have the following snippets of code

from app.models import Packages, PackagesSchema
packages_schema = PackagesSchema()
db.create_all()


and then further down the part which will deal with API GET Requests.

@app.route('/packages', methods=['GET'])
def get_packages():
result = packages_schema.dump(Packages).data
return jsonify(result)


at the moment this returns:

{
"email": "Packages.email",
"localid": "Packages.localid",
"trackingnumber": "Packages.trackingnumber"
}


However, there is definitely something in the database as the Flask-Admin app displays its.

This is my first day working with Flask-Marshmallow so I am not that experienced at all and would appreciate any help. I have read
https://flask-marshmallow.readthedocs.io/en/latest/
but still stuck.

Answer

I just brushed up a little on marshmallow:

@app.route('/packages', methods=['GET'])
def get_packages():
    packages = Packages.query.all()
    result = packages_schema.dump(packages).data
    return jsonify(result)

Should give you everything in there. If you are returning many records, you need to add packages_schema = PackagesSchema(many=True).

Also, not sure what version of flask you are running... but pre the latest release, I dont think jsonify would work here since you could not call it on a list. Juts a heads up.