POST without body on DRF

Viewed 659

I am writting an API on Django Rest Framework to follow users. I define a method POST method to follow, but a body is required. I want to do without body or a default body. If I replace POST with GET works, If is it possible and how can I do?

class UserProfileViewSet(ModelViewSet):

    serializer_class = UserProfileSerializer
    queryset = UserProfile.objects.all()
    filter_backends = (filters.SearchFilter,)
    search_fields = ('name', 'email')
    permission_classes = (UpdateOwnProfile,)

    @action(methods=['POST'], detail=True, url_path='follow')
    def follow(self, request, pk=None):
        user_to_follow = UserProfile.objects.get(pk=pk)
        request.user.add_relationship(
            user_to_follow, RELATIONSHIP_FOLLOWING)
        return Response([], status=status.HTTP_200_OK)
2 Answers

If your serializer class serializer_class = UserProfileSerializer has fields that are required then the form body is required. If you don't want them to be required you can explicitly disable it or make the fields readonly with seralizers.ReadOnlyField()

If you are getting an error, showing your stacktrace would help in resolving it.

Let's say you have a CBV as the following

class SomeView(generics.GenericAPIView):
    serializer_class = SomeSerializer

    def post(self, request, some_id):
        ...

to achieve what you want it should be sufficient to change the serializer_class value to None.

class SomeView(generics.GenericAPIView):
    serializer_class = None

    def post(self, request, some_id):
        ...

Then you will see in the DRF web ui that no body has to be added to the POST request.

Related