I am a little new to DRF (and programming in general), but I have not found a solution to what I am trying to do. I am building an API that allows the user to specify url suffixes with format_suffix_patterns. In particular, JSON, CSV and XML. I have added the renderes for these (in that order) to my DEFAULT_RENDERER_CLASSES.
If I specify the suffix this works perfectly. However I anticipated that by listing the JSONRenderer first that would be the default should no format be specified - but this is not always the case.
From a casual glance it seems the order the renderer is decided is:
1. if specified as a kwarg in the APIView "initial" method
2. if specified as a request parameter in the negotiation "select_renderer" method
3. the request header in the negotiation "select_renderer" method
4. order of renderer ??? I didn't get this far
In some request headers "application/xml" is specified (for example if just hitting the API in a chrome browser). Because I have an XmlRenderer this is selected as default.
I am wondering what the best way to specify "Use this format" and inject it between #2 and #3. As a pretty ugly way I did this in the negotiation.py/select_renderer:
def select_renderer(self, request, renderers, format_suffix=None):
"""
Given a request and a list of renderers, return a two-tuple of:
(renderer, media type).
"""
# Allow URL style format override. eg. "?format=json
format_query_param = self.settings.URL_FORMAT_OVERRIDE
format = format_suffix or request.query_params.get(format_query_param) or settings.DEFAULT_RESPONSE_FORMAT
I imported my settings into the file and specified a format. I would prefer to add this to the REST_FRAMEWORK settings but haven't figure that out yet...and still I think this is bad/hacky solution. Is there something more elegant out there I just haven't found?