2

I would like to limit the access to myweb/api in Django rest framework.

I've tried:

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    )
}

But it limits all the requests however I want to limit access only to myweb/api page.

2

1 Answer 1

5

You could add liberal permissions in settings.py file and add more restrictive ones in the specific api view.

In settings.py, add something like :

'DEFAULT_PERMISSION_CLASSES': (
    'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
),

of you could also use AllowAny permission.

You can set the authentication policy on a per-view, or per-viewset basis, using the APIView class based views.

from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        content = {
            'status': 'request was permitted'
        }
        return Response(content)

Or, if you're using the @api_view decorator with function based views.

from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

@api_view('GET')
@permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)

When you set new permission classes through class attribute or decorators you're telling the view to ignore the default list set over the settings.py file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.