Django Rest API using Django REST Framework- ViewSets

In the introductory part, we learn about generic views. Today we start ViewSets and develop REST API using Django REST Framework with ViewSets. It’s a very different concept to write API in a more dynamic and robust process. Let’s create a serializer class in file named ArticleSerializer and follow below coding snippet:

from codekitapp.models import Category, Article
class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = "__all__"

Now import this ArticleSerializer class into and create another class in named ArticleAPIView which will inherit ViewSet of viewsets interface. Then we add some different functions to get the list of articles, to retrieve an article. Follow the code:

class ArticleAPIView(viewsets.ViewSet):
    def list(self, request):
        queryset = Article.objects.all()
        serializer = ArticleSerializer(queryset, many=True)
        return Response(

    def retrieve(self, request, pk=None):
        queryset = Article.objects.all()
        user = get_object_or_404(queryset, pk=pk)
        serializer = ArticleSerializer(user)
        return Response(

Here list() function will retrieve all the data from Article and retrieve function will only retrieve a single article object. Let’s create a route for this class.

from rest_framework.routers import DefaultRouter
from codekitapp.views import ArticleAPIView
router.register('article', ArticleAPIView, basename='article')
urlpatterns = [
    path('', include(router.urls))

Now if we visit, we will see all article list and if we give an id as a parameter after this URL with a slash like, we will get an article object of id=1.

We can make a more simplified version of it. Let’s create rewrite the ArticleAPIView class with ModelViewSet and remove all functions like below:

class ArticleAPIView(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    queryset = Article.objects.all()

It will implement all 4 endpoints for the article model

  1. [GET]
  2.{id} [GET]
  3.{id} [DELETE]
  4. [POST]
    Body for the post method:
    "title": "",
    "content": "",
    "image": null,
    "category": null,
    "author": null

5.{id} [POST]
body of the PUT method will be like POST method.

It will give you full control of a CRUD system and it is possible with just a single view model.

You will get full source code from here.


About Author


Welcome to I am working in an automation company as a software engineer. From the deep thirst of learning, I have developed this platform.