Search code examples
pythonflaskflask-restful

Can flask-restful return Response object?


When implementing REST API with Flask-Restful, I wanted to return a Flask's Response object, because it is flexible and easy to use. For example:

return Response(
            response=jsonify({
                "data": {
                    "import_id": import_id
                }
            }),
            status=201,
            mimetype="application/json"
        )

But looks like flask-restless doesn't support such a thing:

2019-08-05 08:52:30,077 werkzeug     INFO     172.21.0.1 - - [05/Aug/2019 08:52:30] "POST /imports HTTP/1.1" 500 -
2019-08-05 08:52:30,078 werkzeug     ERROR    Error on request:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/werkzeug/serving.py", line 303, in run_wsgi
    execute(self.server.app)
  File "/usr/local/lib/python3.7/site-packages/werkzeug/serving.py", line 293, in execute
    for data in application_iter:
  File "/usr/local/lib/python3.7/site-packages/werkzeug/wsgi.py", line 507, in __next__
    return self._next()
  File "/usr/local/lib/python3.7/site-packages/werkzeug/wrappers/base_response.py", line 45, in _iter_encoded
    for item in iterable:
TypeError: 'Response' object is not iterable

If there are any workaround to use Response? If not, how can I return a mimetype with flask-restfull?


Solution

  • jsonify() function returns a flask.Response() object, while json.dumps(obj) Serializes obj to a JSON-formatted string.

    
    ....
    from Flask import json, Response
    
    ....
       return Response(
            response=json.dumps({
                "data": {
                    "import_id": import_id
                }
            }),
            status=201,
            mimetype="application/json"
        )