Django Rest Framework for Calculations

Viewed 115

I'm starting to develop in django/django rest framework and I needed to make a kind of calculator, send a and b, python would take these values, process, for example, do the sum and return in a json, but I only find examples with database data, would it be possible to do this?

1 Answers

Try Function-Based Views

You can pass the values of a and b using URL param into view, and could return the response after calculations.

Example:

# views.py
# imports 
from rest_framework.decorators import api_view
from rest_framework.response import Response

# function-based view
@api_view(['POST'])
def calculate(request, a, b):
    result = a + b 
    return Response({"message": f"{result}"})

urls.py would look like this;

# imports
from django.urls import path
from . import views as views # if urls.py and views.py are in same dir

urlpatterns = [
     path('calculate/<int:a>/<int:b>/',
         views.calculate, name="calculate"),
]

It's not mandatory to use function-based views. but that made it easier to achieve functionally what you wanted.

Related