M Hari
M Hari

Reputation: 113

How can I limit http method to a Django REST api

How can I change the api_view decorator in the Function Based View to Class Based View? My requirement is, I want to limit the HTTP access methods such as GET, POST, PUT etc to a particular API

@api_view(['GET', 'POST'])
def hello_world(request):
    if request.method == 'POST':
        return Response({"message": "Got some data!", "data": request.data})
    return Response({"message": "Hello, world!"})

Hope someone know the answer .....

Upvotes: 3

Views: 3526

Answers (3)

user7500581
user7500581

Reputation:

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']

Upvotes: 6

Peconia
Peconia

Reputation: 555

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.

Upvotes: 2

SHIVAM JINDAL
SHIVAM JINDAL

Reputation: 2974

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)

Upvotes: 3

Related Questions