Python Flask, TypeError: 'dict' object is not callable Python Flask, TypeError: 'dict' object is not callable flask flask

Python Flask, TypeError: 'dict' object is not callable


Flask only expects views to return a response-like object. This means a Response, a string, or a tuple describing the body, code, and headers. You are returning a dict, which is not one of those things. Since you're returning JSON, return a response with the JSON string in the body and a content type of application/json.

return app.response_class(rety.content, content_type='application/json')

In your example, you already have a JSON string, the content returned by the request you made. However, if you want to convert a Python structure to a JSON response, use jsonify:

data = {'name': 'davidism'}return jsonify(data)

Behind the scenes, Flask is a WSGI application, which expects to pass around callable objects, which is why you get that specific error: a dict isn't callable and Flask doesn't know how to turn it into something that is.


Use the Flask.jsonify function to return the data.

from flask import jsonify # ...return jsonify(data)


If you return a data, status, headers tuple from a Flask view, Flask currently ignores the status code and content_type header when the data is already a response object, such as what jsonify returns.

This doesn't set the content-type header:

headers = {    "Content-Type": "application/octet-stream",    "Content-Disposition": "attachment; filename=foobar.json"}return jsonify({"foo": "bar"}), 200, headers

Instead, use flask.json.dumps to generate the data (which is what jsonfiy uses internally).

from flask import jsonheaders = {    "Content-Type": "application/octet-stream",    "Content-Disposition": "attachment; filename=foobar.json"}return json.dumps({"foo": "bar"}), 200, headers

Or work with the response object:

response = jsonify({"foo": "bar"})response.headers.set("Content-Type", "application/octet-stream")return response

However, if you want to literally do what these examples show and serve JSON data as a download, use send_file instead.

from io import BytesIOfrom flask import jsondata = BytesIO(json.dumps(data))return send_file(data, mimetype="application/json", as_attachment=True, attachment_filename="data.json")