I recently began using class-based views in the development of Django rest APIs.
While discussing this with a friend, he inquired, "What if I have the same type of request multiple times in the same class?"
because, as stated in the rest documentation, I created post
functions for POST requests and get
functions for GET requests.
So, how to write two GET or other types of requests within the same class?
CodePudding user response:
Was trying out the earlier accepted answer, does not seem to be correct.
The below solution is what shall work for you.
For multiple GET request in same api you need to implement Django Viewset and routers.
I found the below link to be well explained with examples: https://testdriven.io/blog/drf-views-part-3/
CodePudding user response:
In Django REST framework, you can define multiple request methods (e.g. GET, POST, PUT, DELETE) in a class-based view by defining corresponding methods with the same name as the request method. For example, to handle a GET request, you can define a get method in your view class. Here's an example of a class-based view that defines both a get method to handle GET requests and a post method to handle POST requests:
from rest_framework.views import APIView
from rest_framework.response import Response
class MyView(APIView):
def get(self, request, format=None):
# Handle the GET request
data = {"key": "value"}
return Response(data)
def post(self, request, format=None):
# Handle the POST request
data = {"key": "value"}
return Response(data)
You can also use the @api_view decorator to define function-based views that can handle multiple request methods. For example:
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(["GET", "POST"])
def my_view(request):
if request.method == "GET":
# Handle the GET request
data = {"key": "value"}
return Response(data)
elif request.method == "POST":
# Handle the POST request
data = {"key": "value"}
return Response(data)
Note that you can also use the @list_route
and @detail_route
decorators to define additional methods for a class-based view, or use the @action
decorator to define methods for a function-based view that can handle multiple request methods.