Django Rest Framework - Envelope for response

Viewed 633

I'm wanting to convert an API from flask to Django Rest Framework. Currently, the requirements are that the responses are put inside of a basic json structure.

eg.

{
    "status": "success",
    "data": {actual results here}
}

What's the best way to do this?

2 Answers

You can create a custom response:

from rest_framework.response import Response

class CustomSuccessResponse(Response):
    def __init__(self, data=None):
        result = {
            'status': 'success',
            'data': data,
        }
        super(CustomSuccessResponse, self).__init__(data=result)

And then in your view you can use it like this:

 return CustomSuccessResponse(data={'message': 'actual results'})
Related