Forcing application/json MIME type in a view (Flask) Forcing application/json MIME type in a view (Flask) flask flask

Forcing application/json MIME type in a view (Flask)


If you use:

from flask import jsonify

and then in your code:

return jsonify(somedict)

then jsonify() automatically sets the mime type to 'application/json'

Edit:

This was previously considered a risk, but not anymore, and Flask has also updated its recommendation: "ECMAScript 5 closed this vulnerability, so only extremely old browsers are still vulnerable. All of these browsers have other more serious vulnerabilities, so this behavior was changed and jsonify() now supports serializing arrays." http://flask.pocoo.org/docs/1.0/security/#json-security


Like soulseekah noticed, make_response is probably a better option in this case. Then set the mimetype property.

r = make_response( data )r.mimetype = 'application/json'return r