Ask Your Question
4

How can custom requests be implemented in Django REST Framework?

asked 2023-06-22 09:16:19 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-22 09:25:02 +0000

devzero gravatar image

Custom requests can be implemented in Django REST Framework by creating a new view that extends the APIView class, then defining the required HTTP methods and handling the request and response objects in the desired way. For example, here is an example implementation of creating a custom request to get a specific user's profile:

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserProfile
from .serializers import UserProfileSerializer

class UserProfileView(APIView):
    def get(self, request, user_id):
        try:
            user_profile = UserProfile.objects.get(user_id=user_id)
            serializer = UserProfileSerializer(user_profile)
            return Response(serializer.data)
        except UserProfile.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

In this example, we create a new view named UserProfileView that extends the APIView class. We define a GET method that takes a user_id parameter and attempts to retrieve the corresponding UserProfile object from the database. If the object exists, we serialize it using the UserProfileSerializer and return the resulting data as a response. If the object does not exist, we return a 404 not found status code. To use this custom request, we would add a new URL pattern to our project's urlpatterns, mapping the UserProfileView to a URL such as /users/<user_id>/profile.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-22 09:16:19 +0000

Seen: 13 times

Last updated: Jun 22 '23