Get data from a APIview in django rest framework

Question:

In my app I am trying to get the User data using a get request and it works in Postman but the problem occurs when I try to send the data from FrontEnd as we cannot send Body in get Request

URL:

           path('user/meta/', UserDetails.as_view()),

Views.py

class UserDetails(APIView):
    """Get basic details of user"""

    def get(self, request):

        username = request.data["username"]
        if User.objects.filter(username = username).exists():

            user = User.objects.get(username = username)
            print(user)

            return Response({
                'verified': user.verified,
            })
        else:
            return Response("User doesn't exists", status=status.HTTP_400_BAD_REQUEST)

How should I modify it such that I can get the data from get request?

Asked By: Rahul Sharma

||

Answers:

So, your requesting URL will become

/user-info/?username=john

and then, use request.GET

 username = request.GET.get("username","default_value")
Answered By: JPG

The good practice is to use query params in such case,

so your url will look like,

/user-info/?username=john

and you modify your code to,

    username= self.request.query_params.get('username')
Answered By: ShrAwan Poudel

I know this is an old topic and the question is answered, but just to underline that the queried data, you obtained from the user in the API should go through the Serializers (https://www.django-rest-framework.org/tutorial/1-serialization/) to at least somehow protect against unwanted values. This will also avoid you directly querying the database models.

Answered By: Crt Mori