Skip to content

Viewset vs APIView

The differences between APIView and Viewset vary depending on the particular needs and requirements. Therefore, we can provide a code-based example to decide which method should be used:

APIView vs viewsets

Now let’s do the same operations using Viewset:

class BlogPostViewSet(viewsets.ModelViewSet):
    queryset = BlogPost.objects.all()
    serializer_class = BlogPostSerializer

At this point, we wrote less code using Viewset compared to the previous example created with APIView. Viewset contains several predefined methods that can be used for multiple operations, making model operations easier. Also, for customized operations, Viewset can be easily extended with extra methods provided by the Django Rest Framework.

In addition, routers combined with Viewset can automatically match URLs and associate them with the view class, allowing us to easily perform URL routing. This is especially useful in large-scale projects or projects that work with many models.

router = routers.DefaultRouter()
router.register(r'blog-posts', BlogPostViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

In this example, the router element registers our Viewset class and automatically generates the URLs required for the predefined CRUD operations. Thus, you can perform basic CRUD operations by sending GET, POST, PUT, PATCH and DELETE requests to the URL “/blog-posts/”.

Conclusion

  • APIView is derived from Django’s base View class, while Viewset is derived from a special ViewSet class of the Django Rest Framework.

Reference