Skip to main content

authentication private method on class APIView

Sometimes we only need a private route for the method GET, POST, or DELETE. So for implementation, the only private route method we can use is the decorator form in Django.

for example, like below

from rest_framework import permissions
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework.decorators import permission_classes

class MyView(APIView):
authentication_classes = [JWTAuthentication] # Menggunakan JWT Authentication untuk view ini

def get(self, request):
# Public method (no authentication required)
return Response({"message": "This is a public GET method"})

@permission_classes([permissions.IsAuthenticated]) # Menambahkan permission untuk method POST
def post(self, request):
# Private method (authentication required)
return Response({"message": "This is a private POST method!"})

@action(methods=['get'], detail=False)
@permission_classes([permissions.IsAuthenticated]) # Private GET method
def private_get(self, request):
return Response({"message": "This is a private GET method!"})