Katsuya Obara
Katsuya Obara

Reputation: 963

are there any way to aggregate multiple API result into single API in Django Rest Framework?

I have following URL set which returns JSON API. Now I wonder is there any way to create another API which aggregates all of these API results and return to one ajax call from client side lets say,url(r'^api/allData/(?P<pk>\d+)$',allData.as_view())
Does anyone know how to prepare class in views.py to achieve this?

urlpatterns = [
    url(r'^api/envelope/(?P<pk>\d+)$',envelopeData.as_view(),name='api-envelope'),
    url(r'^api/glass/(?P<pk>\d+)$',glassData.as_view(),name='api-glass'),
    url(r'^api/opaque/(?P<pk>\d+)$',opaqueData.as_view(),name='api-opaque'),
    url(r'^api/plant/(?P<pk>\d+)$',plantData.as_view(),name='api-plant'),
    url(r'^api/fan/(?P<pk>\d+)$',fanData.as_view(),name='api-fan'),
    url(r'^api/pump/(?P<pk>\d+)$',pumpData.as_view(),name='api-pump'),
    url(r'^api/people/(?P<pk>\d+)$',peopleData.as_view(),name='api-people'),
    url(r'^api/light/(?P<pk>\d+)$',lightData.as_view(),name='api-light'),
    url(r'^api/smallpower/(?P<pk>\d+)$',spData.as_view(),name='api-sp'),
]

Upvotes: 1

Views: 273

Answers (2)

JPG
JPG

Reputation: 88569

Seems like you are using APIView. So, You could call the get() post() methods of the view by using their class object.

Here is one Example

from rest_framework.views import APIView
from rest_framework.response import Response


class MyView_One(APIView):
    def get(self, request, pk, *args, **kwargs):
        return Response(data={"message": self.__class__.__name__})


class MyView_Two(APIView):
    def get(self, request, pk, *args, **kwargs):
        return Response(data={"message": self.__class__.__name__})


class MyView_Three(APIView):
    def get(self, request, pk, *args, **kwargs):
        return Response(data={"message": self.__class__.__name__})


class My_All_View(APIView):
    def get(self, request, pk, *args, **kwargs):
        return_data = {}
        one = MyView_One()
        return_data.update({"one": one.get(request, pk).data})
        two = MyView_Two()
        return_data.update({"two": two.get(request, pk).data})
        three = MyView_Three()
        return_data.update({"three": three.get(request, pk).data}
        return Response(data=return_data)


Use this My_All_View in your urls.py as any other views

Screenshot
enter image description here

Upvotes: 4

Ali
Ali

Reputation: 2591

You can use nested serializer, for example:

class Serializer1(Serializer):
    ...

class Serializer2(Serializer):
    ....

class Serializer3(Serializer):
    serializer1 = Serializer1()
    serializer2 = Serializer2()

    class Meta:
        fields = ('serializer1', 'serializer2')

But about merging views, I do not think.

Upvotes: 0

Related Questions