user2348945
user2348945

Reputation: 11

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

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

I three kind of users.

Different kind of users should have access to different APIs

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.)

Upvotes: 1

Views: 42

Answers (1)

Ali Rn
Ali Rn

Reputation: 1214

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

Upvotes: 4

Related Questions