Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework - Envelope for response

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?

like image 416
InsanelyADHD Avatar asked Mar 08 '23 22:03

InsanelyADHD


2 Answers

A generic approach would be to inherit from the DRF's JSONRenderer and adapt it to your needs, see http://www.django-rest-framework.org/api-guide/renderers/.

Aditionally you propably want to adapt the pagination style to your old flask api, see http://www.django-rest-framework.org/api-guide/pagination/.

like image 90
Johannes Reichard Avatar answered Mar 28 '23 04:03

Johannes Reichard


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'})
like image 33
Jahongir Rahmonov Avatar answered Mar 28 '23 05:03

Jahongir Rahmonov