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

PythonJsonMime TypesFlask

Python Problem Overview


I can't figure out how to force the MIME type application/json for a view in Flask. Here is a simple view I've thrown together for demonstration purposes:

@app.route("/")
def testView():
    ret = '{"data": "JSON string example"}'
    return ret

The JSON string (held in variable ret) is gathered from elsewhere (using stdout from another program using subprocess) so I can't use jsonify provided with Flask.

I've had a look at the "Returning Json" Documentation and this Stackoverflow question but I haven't had any luck so far. I've been looking around for awhile now & will continue searching but thought I'd ask here just in case anyone has come across this.

Thanks.


See the answer below

The solution:

@app.route("/")
def testView():
    ret = '{"data": "JSON string example"}'

    resp = Response(response=ret,
                    status=200,
                    mimetype="application/json")

    return resp

I found this website useful: Implementing a RESTful Web API with Python & Flask

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJayView Question on Stackoverflow
Solution 1 - PythonProf. FalkenView Answer on Stackoverflow
Solution 2 - PythonAdam BaxterView Answer on Stackoverflow