4

I am met with a situation where my frontend guy needs the response in the following format from all of my endpoints.

{ status: 200, message: "OK", content: {Normal DRF Response Body} }

I know that I can get this structure by using the APIView in all of my views but then I will not be able to use generic views or viewsets.

I was thinking if there is any way to extend the DRF Response class and specify the extended class in settings.py or maybe use a Middleware for this purpose.

What can be done for this?

Enthusiast Martin
  • 3,041
  • 2
  • 12
  • 20
Huzaifa Qamer
  • 314
  • 2
  • 4
  • 17

1 Answers1

3

Yes, there is.

You can implement your renderer and add it to your settings.py like this :

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        '< your renderer >',       
    ),  
}

And for the actual renderer - take inspiration from the rest_framework's JSON renderer ( rest_framework.renderers.JSONRenderer ).

You can basically take the implementation of this JSONRenderer and change render function slightly.

  def render(self, data, accepted_media_type=None, renderer_context=None):
    """
    Render `data` into JSON, returning a bytestring.
    """

Here you will have access to data and renderer_context. The context has response object which is your response. It has 'status_code' attribute which you can use in your response.

response = renderer_context['response']
my_response = { "status" : response.status_code,
                "message" : "OK",
                "content" : data }

For the message, it is up to you where you get correct message for given status code.

Then, if you follow the original JSONRendener implementation, you can find the following snippet and you can just change it to dump your new response:

ret = json.dumps(
        my_response, cls=self.encoder_class,
        indent=indent, ensure_ascii=self.ensure_ascii,
        allow_nan=not self.strict, separators=separators
    )
Enthusiast Martin
  • 3,041
  • 2
  • 12
  • 20
  • But this seems to work only for list and create. There is no msg and status in update, and no response body in destroy. – shuiqiang Jul 01 '19 at 12:19