RESTful interface in Flask and issues serializing RESTful interface in Flask and issues serializing flask flask

RESTful interface in Flask and issues serializing


I would use a module to do this, honestly. We've used Flask-Restless for some APIs, you might take a look at that:

https://flask-restless.readthedocs.org/en/latest/

However, if you want build your own, you can use SQLAlchemy's introspection to output your objects as key/value pairs.

http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html#metadata-reflection

Something like this, although I always have to triple-check I got the syntax right, so take this as a guide more than working code.

@app.route('/tasks')def tasks():    tasks = Tasks.query.all()    output = []    for task in tasks:      row = {}      for field in Tasks.__table__.c:        row[str(field)] = getattr(task, field, None)      output.append(row)    return jsonify(data=output)

I found this question which might help you more. I'm familiar with SQLAlchemy 0.7 and it looks like 0.8 added some nicer introspection techniques:

SQLAlchemy introspection


Flask provides jsonify function to do this. Check out its working here.

Your json_dump method is right though code can be made concise. See this code snippet

@app.route('/tasks')def tasks():    tasks = Tasks.query.all()    return jsonify(data=[c.json_dump() for c in tasks])