Views in Django REST Framework

Jan. 12, 2023


3
4 min read
401

In this article we know about Django REST framework views. In the Django REST framework, views handle the incoming HTTP requests and return the appropriate response. There are several different types of views that can be used, including:

  • APIView: This is the basic building block for creating views in the Django REST framework. It provides a simple and consistent class-based interface for handling incoming requests and returning responses.

  • GenericAPIView: This is a subclass of APIView that provides more generic implementations of common functionality. It includes support for pagination, filtering, and other common functionality.

  • ViewSet: A viewset is a class that defines the actions that can be performed on a model using a RESTful API, such as listing, creating, updating and deleting instances of the model.

  • ModelViewSet: This is a subclass of ViewSet that is specifically designed to work with Django models. It provides an implementation for the list, creates, retrieves, update and delete operations.

  • ListAPIView : This class-based view is used to display a list of objects. It provides a get method handler to handle the GET request to retrieve the list of objects.

  • RetrieveAPIView : This class-based view is used to display details of a specific object. It provides a get method handler to handle the GET request to retrieve the object details.

Each of these views can be further customized to meet your specific requirements.

Here's an example of using the APIView class to handle a simple GET request:

from rest_framework.views import APIView
from rest_framework.response import Response

class MyView(APIView):
    def get(self, request):
        data = {'message': 'Hello, World!'}
        return Response(data)

This view simply returns a dictionary containing a single key-value pair. When a GET request is made to the endpoint corresponding to this view, the server will return a JSON object containing the message "Hello, World!".

Here's an example of a ModelViewSet:

from rest_framework import viewsets
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

This viewset will handle the CRUD operations on the MyModel model and it expects the MyModelSerializer to serialize and deserialize the data.

You can also use generic views like ListAPIView and RetrieveAPIView

from rest_framework import generics
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelListView(generics.ListAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

class MyModelDetailView(generics.RetrieveAPIView):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

In this example, MyModelListView will handle the GET request to list all the objects of MyModel model and MyModelDetailView will handle the GET request to retrieve the details of a specific object of MyModel model.

These are just a few examples of how views can be used in Django REST framework. There are many other options and customization available to handle different types of requests and responses.

You can also use function-based views in Django REST framework. Here is an example of a simple function-based view that handles a GET request:

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def my_view(request):
    data = {'message': 'Hello, World!'}
    return Response(data)

In this example, the api_view decorator is used to indicate that this function should only handle GET requests. The function simply returns a dictionary containing a single key-value pair, which will be sent back to the client as a JSON object.

You can also use the @action decorator to define custom actions for your views.

from rest_framework import viewsets
from .models import MyModel
from .serializers import MyModelSerializer

class MyModelViewSet(viewsets.ModelViewSet):
    queryset = MyModel.objects.all()
    serializer_class = MyModelSerializer

    @action(methods=['get'], detail=False)
    def custom_action(self, request):
        # Your custom action logic here
        data = {'message': 'Custom Action'}
        return Response(data)

This viewset will handle the CRUD operations and it also have a custom action custom_action which can be accessed by appending /custom_action to the endpoint.

These are just a few examples of how views can be implemented in Django REST framework. The key is to understand the different types of views available and how they can be used to handle different types of requests and responses.

Please let me know in the comment if you have any other questions.

views API django-rest-framework REST-APIs Appreciate you stopping by my post! 😊

Comments


Profile Picture

Abdulla Fajal

Very informatics

Jan. 12, 2023, 4:58 p.m.

Profile Picture

@Alvin

Its really cool

Jan. 13, 2023, 1:10 p.m.

Profile Picture

Zehra Ahmad

Thanks #alvin

Jan. 13, 2023, 11:33 p.m.

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required