Search code examples
pythonflaskflask-restplus

remove whitespace from JSON response by flask-restplus


How can you get rid of whitespace in the JSON response by flask-restplus routes?

In a similar question, but for flask-restful instead of flask-restplus, the answer suggested setting the config option JSONIFY_PRETTYPRINT_REGULAR = False. This does not seem to work for flask-restplus.

I can't find anything in the documentation for flask-restplus around this either. What's the right way to do this? Anything better than overwriting the response handler?


Solution

  • Glancing at the source, flask-restplus takes it JSON dumps settings from a flask config variable called RESTPLUS_JSON. But also from the source, it looks like it would only pretty-print when running in debug mode.

    Here's an example of manually controlling it:

    from flask import Flask
    from flask_restplus import Api, Resource
    app = Flask(__name__)
    api = Api(app)
    app.config['RESTPLUS_JSON'] = {'indent':None, 'separators':(',',':')}
    
    @api.route('/hello')
    class HelloWorld(Resource):
        def get(self):
            return {'hello': 'world', 'abc':'def'}
    
    if __name__ == '__main__':
        app.run(debug=True)