Search code examples
pythonflask-restfuljsonify

Using jsonify with FlaskRESTful returns me a TypeError


app = Flask(__name_))
api = Api(app)

class MyClass(Resource):
    def post(self):
        # Here i call a function from a separate file, which returns me a big python dict
        result = my_func()
        
        return jsonify(result), 200

This returns me the following error:

TypeError: Object of type Response is not JSON serializable

I tried adding:

test = jsonify(result), 200

And there is not error, so this means the endpoint return throws me an error? I do not understand, does Flask-RESTful call jsonify by default or something?


Solution

  • You do not have to use jsonify() function, as the framework's core functionality includes automatic JSON serialization for resource methods. This means that when you return a Python object from a POST function, Flask-RESTful will automatically convert it into a JSON-formatted string.

    app = Flask(__name_))
    api = Api(app)
    
    class MyClass(Resource):
        def post(self):
            # Here i call a function from a separate file, which returns me a big python dict
            result = my_func()
            
            return result, 200