I am trying to switch over my REST server from just Flask to Flask-RESTful.
What I am confused with is, I am using retrofit to read the data on the client, but on the first instance I need to use json.dumps(data) and the second I just need to return.
Can anyone explain this? In both bits of code data is a list
First example just Flask
data = []
for row in cur.fetchall():
out = {
"list_id": row[0],
"list_name": row[1]
}
data.append(out)
cur.close()
return json.dumps(data)
Second example Flask-RESTful
class UserLists(Resource):
def get(self, user_id):
results = Lists.query.filter(Lists.user_id == user_id).all()
data = [{'list_id': list_item.id, 'list_name': list_item.name} for list_item in results]
return data
Flask-RESTful takes care of encoding the response for you. It is not limited to returning just JSON, it will encode to supported formats based on the requested format from the client (set via the Accept
request header).
See the Content Negotiation chapter to learn how to add format support other than the default JSON output.
As such, for a Flask-RESTful response you need to return a Python structure, not JSON-encoded data, as that would preclude producing, say, an XML or CSV response if you wanted to support such formats in the future.