Flask jsonify returns Response. How to provide status code?

2.6k views Asked by At

I sow a lot of examples where developers have the following expression:

return jsonify(data), 200

Even in my last work project I had the same expression, but now, when I'm trying to write my new project, I catch the following error:

TypeError: Object of type Response is not JSON serializable

If I return only the result of jsonify(), it works but returns the 200 status code. I want to control the code. It doesn't work with flask_restful.Resource.

Seems like jsonify() returns Response object. How to fix it?

3

There are 3 answers

4
c8999c 3f964f64 On

flask-restful uses jsonify already.

if you use jsonify with flask-restful, it tries to jsonify a response twice.

simply do this:

return data, 200
1
papillontrail On

Sounds like data is a Response object, and the code is choking when you try to serialize that into JSON. Try return jsonify(data.text), 200.

If that doesn't work, we need more code to diagnose this.

0
Jesus21282 On

I was getting the same error, and ended up applying Dzianis Talkachou's workaround to prevent it:

Wrapping the jsonify response in a make_response will do the trick.

from flask import jsonify, make_response
...
return make_response(jsonify(your_data), 200)