Instagram
youtube
Facebook
Twitter

Class Based API View

In this tutorial, we'll learn how to create a simple class-based API view using Django REST Framework (DRF). Class-based views offer a structured and reusable way to handle API requests and responses. We'll build an API view for managing a basic students data.

Here, we will create a simple API to manage the student records that we created in our previous tutorial. It is almost similar to the function-based views tutorial; the only difference is that here we'll use class-based views.

What are the advantages of Class-Based Views?

Some main advantages of Class-Based views are:

  • Code Reusability: CBVs promote code reusability through inheritance and mixins.

  • Modularity: CBVs encourage separating concerns by using different methods for different HTTP methods.

  • Built-in Behavior: DRF provides generic views and mixins that handle common tasks like CRUD operations, pagination, and authentication.

  • Complex Logic: They're well-suited for views with multiple interactions, different data representations, and complex logic.

Create Serializers

In serializers.py file create a serializer for the 'students' model.

from rest_framework import serializers
from .models import Students

class StudentsSerializer(serializers.ModelSerializer):
    class Meta:
        model = Students
        fields = '__all__'

Create API Views

In views.py file we'll create api views to perform 'GET' and 'POST' operations.

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import Students
from .serializers import StudentsSerializer

class student_list(APIView):
    def get(self, request):
        students = Students.objects.all()
        serializer = StudentsSerializer(students, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = StudentsSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

So, here we have create an simple Class-Based api API to perform GET and POST operations. We can simply perform GET operation using ' http://localhost:8000/students/' and POST operation by sending a request on URL with JSON data. 

Now, lets check our API view is working or not....

Properly Working!!