Flask api representation affects all the views Flask api representation affects all the views flask flask

Flask api representation affects all the views


Firstly, please note that you should not use the same resource to return either a single action or a list of actions. You should use two different resources:

class Action(flask_restful.Resource):    def get(self, action_id):        return actions[action_id]class ActionList(flask_restful.Resource):    def get(self):        return actions

Then, the simplest way to return different media types for the same resource is to use content negotiation. In this case, you do not need to declare a dedicated resource ActionAsCSV to specifically handle the case of returning a response in CSV format. For example, to use content negotiation with curl:

curl -iH "Accept: text/csv" http://URL_TO_YOUR_VIEW

Moreover, Flask-RESTful automatically add the right content-type header for you in the returned response: you do not need to define it in the get method of your resource.

Also, the API is configured by default to return representations in JSON. However, you can modify that as follow:

api = flask_restful.Api(app, default_mediatype="text/csv")

If you absolutly want two different resources to handle either application/json or text/csv, withous using content negotiation and no fallback media type, this is possible:

api = flask_restful.Api(app, default_mediatype=None)class ActionListMixin(object):    def get(self):        return actionsclass JsonActionList(ActionListMixin, flask_restful.Resource):    representations = {'application/json': output_json}class CsvActionList(ActionListMixin, flask_restful.Resource):    representations = {'text/csv': output_csv}

Anoter similar option is to define representation transformers when adding your resources:

api = flask_restful.Api(app, default_mediatype=None)class ActionList(flask_restful.Resource):    def __init__(self, representations=None):        self.representations = representations        super(ActionList, self).__init__()    def get(self):        return actionsapi.add_resource(ActionList, '/actions_json', resource_class_kwargs={'representations': {'application/json': output_json}})api.add_resource(ActionList, '/actions_csv', resource_class_kwargs={'representations': {'text/csv': output_csv}})