[Django]-How can I limit http method to a Django REST api

6👍

You can use http_method_names as below and hope you using ModelViewSet class.

class UserView(viewsets.ModelViewSet):
    queryset = UserModel.objects.all()
    serializer_class = UserSerializer
    http_method_names = ['get']

3👍

You should use APIView. Methods only you define in class will be permissible.In this only get and post is permissible.

from rest_framework.views import APIView

class SnippetList(APIView):
"""
List all snippets, or create a new snippet.
"""
def get(self, request, format=None):
    snippets = Snippet.objects.all()
    serializer = SnippetSerializer(snippets, many=True)
    return Response(serializer.data)

def post(self, request, format=None):
    serializer = SnippetSerializer(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)

2👍

You can also use the generic class based views. They only provide the appropriate http method handlers, for example generics.RetrieveAPIView only allows GET request. The documentation at lists the generic views and what methods they support.

Leave a comment