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 serializer.py 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 views.py and create another class in views.py 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(serializer.data)

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

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=DefaultRouter()
router.register('article', ArticleAPIView, basename='article')
urlpatterns = [
    ...............
    path('', include(router.urls))
]

Now if we visit 127.0.0.1:8000/api/article, we will see all article list and if we give an id as a parameter after this URL with a slash like 127.0.0.1:8000/api/article/1, 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. 127.0.0.1:8000/api/article/ [GET]
  2. 127.0.0.1:8000/api/article/{id} [GET]
  3. 127.0.0.1:8000/api/article/{id} [DELETE]
  4. 127.0.0.1:8000/api/article/ [POST]
    Body for the post method:
{
    "title": "",
    "content": "",
    "image": null,
    "category": null,
    "author": null
}

5. 127.0.0.1:8000/api/article/{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.

112 Views

About Author

Nasir

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