0

I am new to Django and created simple api which displays message using GET method

views.py:

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

urls.py:

from django.urls import path,include
from django.contrib.auth.models import User
from rest_framework import routers, serializers, viewsets
from . import views

urlpatterns = [
    path('',views.index,name='Home'),
    path('message',views.message,name='message'),
]

Output: enter image description here

Now I want to take 2 inputs from user through url and perform addition on that inputs and return its result using GET and POST methods.

Example: http://127.0.0.1:8000/message/?a=2&b=3 (something like this) and it should return addition results.

Most of tutorials online are on fetching data from database but I want to create api which takes input from user and return its output.

Can anyone show me how to achieve above task?

1
  • you can use request.query_params in your function to access a and b. Jul 24, 2020 at 7:04

1 Answer 1

0

You can use query_params for this:

@api_view(["GET"])
def message(request):
  a = request.query_params.get('a')
  b = request.query_params.get('b')
       
  return Response({"Print": "a = {}, b={}".format(a,b), status=status. HTTP_200_OK)
7
  • Thanks for answering, can you please guide me how to provide values of a and b through URL, when I tried http://127.0.0.1:8000/message/?a=2&b=3 I am getting error as Page not fount and how to achieve this using POST also
    – L Lawliet
    Jul 24, 2020 at 7:13
  • http://127.0.0.1:8000/message/?a=2&b=3 should work just fine. Please verify your urls.py if it is pointing correctly to the view
    – ruddra
    Jul 24, 2020 at 7:16
  • I've edited the question and pasted my urls.py, can you please review it and let me know if any modification needed
    – L Lawliet
    Jul 24, 2020 at 7:22
  • Are you making POST requests?
    – ruddra
    Jul 24, 2020 at 7:23
  • okay, can you try with http://127.0.0.1:8000/message?a=2&b=3 OR change the url to path('message/',views.message,name='message'),?
    – ruddra
    Jul 24, 2020 at 7:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.