No_body
No_body

Reputation: 842

How to display the result in Django API

I just started working on python based Django. I am following this example to create an API.

https://dzone.com/articles/create-a-simple-api-using-django-rest-framework-in

Instead of using POSTMAN I am using my web browser to display the result bu I am getting error. Method 'GET' not allowed. I looked into different answers and concluded that I need to add a 'GET' method I tried changing

@api_view(["POST"]) from 'POST' to 'GET'

but then it throw an error "Expecting value: line 1 column 1 (char 0)".

How can I add a GET here in this view.

@api_view(["POST"])
def IdealWeight(heightdata):
   try:
      height=json.loads(heightdata.body)
      weight=str(height*10)
      return JsonResponse("Ideal weight should be:"+weight+" kg",safe=False)
   except ValueError as e:
      return Response(e.args[0],status.HTTP_400_BAD_REQUEST)

Do I need POSTMAN to view the output? Thanks

Upvotes: 1

Views: 310

Answers (1)

waynetech
waynetech

Reputation: 779

Your Code indentation is wrong. Look at the blog again.
Your function IdealWeight expects a value which it tries to get (using json.loads(heightdata.body)) from your GET request's body. When you use a browser to do a GET request the body is empty. That can cause error or your height will be empty.

If you just want to test the endpoint for GET change like this.

@api_view(["GET"])
def IdealWeight(request):
  if request.method == 'GET':
    return Response({"Print": "GET request from browser works"}, status=status. HTTP_200_OK)

You should use postman for testing POST request as it makes it easy

Upvotes: 1

Related Questions