7

I am writing web service using restful flask. The below code giving me this error - TypeError: is not JSON serializable

from flask import jsonify
from flask_restful import Resource
class Recipe(Resource):
   def get(self):
      return jsonify({"status": "ok", "data": ""}), 200

How ever this code is working fine

from flask import jsonify
from flask_restful import Resource
class Recipe(Resource):
   def get(self):
      return jsonify({"status": "ok", "data": ""})

The Below code is also working

from flask import jsonify
from flask_restful import Resource
class Recipe(Resource):
def get(self):
   return {"status": "ok", "data": ""},200

I have noticed that I get the error when I use jsonify and response code together, I need to use jsonfy because I will be sending object as response.

Codeformer
  • 2,060
  • 9
  • 28
  • 46

1 Answers1

9

Got the solution - Flask has this function called make_response

from flask import jsonify, make_response

class Recipe(Resource):
   def get(self):
   return make_response(jsonify({"status": "ok", "data": ""}), 201)
Édouard Lopez
  • 40,270
  • 28
  • 126
  • 178
Codeformer
  • 2,060
  • 9
  • 28
  • 46
  • 1
    How do U get this json out of the response on the client? Above returns ``. How can I get the dict out of that? ` i.e. `res['status'] => 'ok'` `json.loads(res)` fails – Mote Zart Jan 02 '20 at 20:34
  • Found answer here - https://flask.palletsprojects.com/en/1.1.x/api/#response-objects `res.data` – Mote Zart Jan 02 '20 at 20:54