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.
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:
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.
The next step is to decorate our function at views.py with a newly created decorator
you can see that we also use the
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.