3

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 .....

3 Answers 3

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']
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.