Shankar Guru
Shankar Guru

Reputation: 1161

How to set Request and response "Content-Type" to "application/json;charset=UTF-8"?

In flask restful, based on open API spec, I need to ensure that requests have header Content-Type set to application/json;charset=UTF-8 which means that input request is a JSON and encoded in UTF-8.

I can check for JSON using below code:

if request.is_json:
    do some thing

But, how can I make sure that request and response is UTF-8 encoded and output should also be application/json;charset=UTF-8 ?

Upvotes: 2

Views: 5012

Answers (2)

Lukasz Dynowski
Lukasz Dynowski

Reputation: 13620

You could set JSONIFY_MIMETYPE config to "application/json; charset=utf-8" like this.

from flask import Flask

app = Flask(__name__)
app.config["JSON_AS_ASCII"] = False
app.config["JSONIFY_MIMETYPE"] = "application/json; charset=utf-8"

So next time, you return data like this return jsonify(data) - without messing with response.headers

Upvotes: 2

Adamo Figueroa
Adamo Figueroa

Reputation: 448

You could create a response using jsonify

from flask import Flask, jsonify
...

Then you can change some http properties

response = jsonify({"status": "ok" })
response.status_code = 200
response.headers["Content-Type"] = "application/json; charset=utf-8"
return response

Upvotes: 2

Related Questions