Search code examples
djangodjango-viewsdjango-rest-framework

What are the differences between the APIView and ViewSets classes in Django?


What are the differences between the APIView and ViewSets classes?

I am following Django REST framework official documentation. I find it lacking in examples.

Can you explain the above difference with a suitable example?


Solution

  • APIView is the most basic class that you usually override when defining your REST view. You usually define your methods like get, put, delete and others see: http://www.cdrf.co/3.5/rest_framework.views/APIView.html. With APIView you define your view and add it to your URLs like so:

    # in views.py
    class MyAPIView(APIView):
         ... #here you put your logic check methods you can use
    
    # in urls.py
    url(r'^posts$', MyAPIView.as_view()), #List of all the posts
    

    Because certain things like getting /post/4, deleting /post/4, getting all posts, updating posts, and creating new posts are so common DRF provides ViewSets.

    Before you use ViewSets, let me tell you about Generic Classes. They do things very well, but you need to provide the full API endpoint like I did with my MyAPIView view (again for more info check http://www.cdrf.co/ or http://www.django-rest-framework.org/). So you would have to define your own URL paths.

    But with ViewSets you create ViewSet that actually merges all the above-described operations and also you don't need to define the URL path you, instead you use a router that makes paths for you like this:

     # views.py
     class PostViewSet(ViewSet):  # Here you subclass ViewSet check methods you can override, you have also ModelViewSet,...
    
    
     # urls.py 
     router = routers.DefaultRouter()
     router.register(r'post', PostViewSet, base_name='Post')