Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.