noirbizarre / flask-restplus

Fully featured framework for fast, easy and documented API development with Flask
http://flask-restplus.readthedocs.org
Other
2.73k stars 507 forks source link

@api.representation enforces the results displayed in xml format #459

Open manbeing opened 6 years ago

manbeing commented 6 years ago

Use the following simple code, we will see two output format options (json and xml) in swagger dev portal, however, if we type URL: localhost:5000/dump to browser, it displays xml format rather than json format. It is because of @api.representation. How can I let set json format displayed as default in browser?

import simplexml
from flask import make_response, Flask
from flask_restplus import Resource, Api

app = Flask(__name__)
api = Api(app, default_mediatype='application/json')

@api.representation('application/xml')
def xml(data, code, headers=None):
    resp = make_response(simplexml.core.dumps({'response': data}), code)
    resp.headers.extend(headers or {})
    return resp

@api.route('/dump')
class dump(Resource):
    def get(self):
        return {'result':'dumps returned'}

if __name__ == '__main__':
    app.run('localhost', 5000,debug=True)
0xd61 commented 6 years ago

Its probably because of your default accept header in your browser. For Firefox it is: "Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8" You need to add "application/json" before "application/xml". You can change the Accept string in about:config. Search for the key: network.http.accept.default

You can check your default headers in Developer Tools --> Network of your browser. Just select the GET call and check the request headers.

NandeeshHD commented 4 years ago

adding the below code block worked for me:

@api.representation("text/html")
def output_hmtl(data, code, headers=None):
    resp = make_response(data, code)
    resp.headers.extend(headers or {})
    return resp

Seems bit redundant. Let me know if there is any better was.