Search code examples
pythonjsonrequesthttpresponseflask-restful

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 ?


Solution

  • 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