Search code examples
python-3.xflaskcharacter-encodingflask-restfulurldecode

Unable to decode "devanagari text" passed as URL param


My Python Flask App is unable to decode the devanagari text eg:"सिंगापूर" that I pass as urlparam from my postman. If I sen english text it handles it well.

My PostMan query : GET http://localhost:5000/getSimilarWord/सिंगापूर

from flask import Flask
from flask_restful import Resource, Api

class DevnagriText(Resource):
    def get(self, textInput):
        print("parsed String is :",textInput)
        return {'text': textInput} 

api.add_resource(DevnagriText, '/getWord/<string:textInput>')

if __name__ == '__main__':
    app.run(debug=True)

The output I get on console is

{
    "text": "\u00818"
}

Instead of

{
    "text": "सिंगापूर"
}

Solution

  • You need to prevent the response from forcing ASCII: app.config['JSON_AS_ASCII'] = False

    So in your example:

    
    from flask import jsonify, Flask
    from flask_restful import Resource, Api
    
    app = Flask(__name__)
    app.config['JSON_AS_ASCII'] = False
    api = Api(app)
    
    class DevnagriText(Resource):
        def get(self, textInput):
            print("parsed String is :",textInput)
            return jsonify(text=textInput)
    
    api.add_resource(DevnagriText, '/getWord/<string:textInput>')
    
    if __name__ == '__main__':
        app.run(debug=True)
    

    But, this doesn't really matter, it will all get interpreted the same way if it gets read into Python or JavaScript.