django rest framework drf permissions file code

Django Rest Framework Tips and Tricks

by

in

In this Django rest framework tips article, I will collect interesting and useful tips that can be used while you code your API with Django. I do also have a Django framework tips and tricks article, don’t forget to check.

How to restrict access to Django Rest Framework API for specific users only?

I will show you how to restrict access to the DRF API endpoint on a function-based view.

django rest framework drf permissions file
django rest framework drf permissions file

Let’s start with permissions.py file creation, in this file, we will override the BasePermissions class from rest_framework.permissions and create the new permission class:

UsernamesListPermissions

code for permissions.py:

from rest_framework.permissions import BasePermission

class UsernamesListPermissions(BasePermission):
    """allow certain users to perform API requests"""
    def has_permission(self, request, view):
        #retrn allowed if true, else - false
        list_of_users = ['proximity','tesored']
        return  request.user.username in list_of_users

We list the users in the list_of_users variable, which will be able to send the requests to our DRF endpoint. Those users must be registered as well.

django rest framework drf permissions file code
django rest framework drf permissions file code

The next step is to decorate our function at views.py with a newly created decorator

django rest framework drf permissions decorators
django rest framework drf permissions decorators
@permission_classes

you can see that we also use the

IsAuthenticated

method, which checks if the request has been sent with user-password credentials in the authorization part of the request.  This means that we have 2 layers of permissions restrictions, 1. user must be registered, 2. The user must have the username from the list_of_users as well.

 


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *