How to provice access for specific users to view certain APIs in django rest framework

Viewed 32

I have three APIs created by inheriting APIView class

class API1View(APIView):
    def get(self, request):
        return Response("API 1 view")

class API2View(APIView):
    def get(self, request):
        return Response("API 2 view")

class API3View(APIView):
    def get(self, request):
        return Response("API 3 view")

I have three users

  • user1
  • user2
  • user3

I three kind of users.

  • customer
  • manager
  • employee

Different kind of users should have access to different APIs

  • The Manager can only able to view the API1 and API2
  • The Customer can only able to view the API1
  • The Employee can only able to view the API3

In future, I need to able to revoke access of a certain user to certain API.

Is it good to use Django Groups or is there any better ways to do it? Or is there any DRF way to do it? (I have seen DRF permissions but I'm not sure if that will work for this scenario.)

1 Answers

You can create your custom permissions and use them in your APIs:

from rest_framework.permissions import BasePermission


class CustomerPermission(BasePermission):
    message = 'You Don\'t Have Access To Customer APIs'

    def has_permission(self, request, view):
        return bool(request.user.is_customer)

Usage:

class API3View(APIView):
    permission_classes = [CustomerPermission]
    def get(self, request):
        return Response("API 3 view")

The permission_classes gets multiple permissions but it works like an and if you want to set access to an API for multiple users, you should write custom permission for it too

Related