Search code examples
djangoapicrudendpoint

Same api endpoint for CRUD operations in Django generic apiview


I have been creating different api endpoint for different requests, for eg every single api for get, post, delete and update in generic apiview. But my frontend developer has told me it's a very bad practice and I need to have a single api for all those 4 requests. When I looked it up in the documentation, there is a ListCreateApiView for listing and creating an object, but I cant use it for delete and also for update. How can I include those two in a single endpoint. I don't use modelset view and also functional view. I mostly use generic api views.


Solution

  • Did you try rest framework's ModelViewSet?

    i.e.:

    from rest_framework.viewsets import ModelViewSet
    

    Which has all the mixins (CRUD) and you can inherit from it in your API view. Or you can add these mixins based on your requirements:

    from rest_framework.mixins import CreateModelMixin, ListModelMixin, RetrieveModelMixin, UpdateModelMixin, DestroyModelMixin
    

    and you can inherit from each one of them seperately. For instance:

    Class SomeView(CreateModelMixin, DestroyModelMixin, GenericViewSet):
        pass
    

    which has create and delete ability. You can also use mixins with GenericAPIView:

    Class SomeView(CreateModelMixin, DestroyModelMixin, GenericAPIView):
        pass