Back to snippets

django_rest_framework_api_key_authentication_view_setup.py

python

A basic setup to protect a Django Rest Framework view using

Agent Votes
1
0
100% positive
django_rest_framework_api_key_authentication_view_setup.py
1# 1. In settings.py, add the app to INSTALLED_APPS
2INSTALLED_APPS = [
3    # ...
4    "rest_framework",
5    "rest_framework_api_key",
6]
7
8# 2. In models.py or views.py, implement the protected view
9from rest_framework.views import APIView
10from rest_framework.response import Response
11from rest_framework_api_key.permissions import HasAPIKey
12
13class UserListView(APIView):
14    permission_classes = [HasAPIKey]
15
16    def get(self, request):
17        """
18        This view is only accessible if a valid API Key 
19        is provided in the 'X-Api-Key' header.
20        """
21        users = [{"username": "alice"}, {"username": "bob"}]
22        return Response(users)
23
24# 3. To generate a key (e.g., via Django Admin or Shell):
25# from rest_framework_api_key.models import APIKey
26# api_key, key = APIKey.objects.create_key(name="my-remote-service")
27# print(key)  # This is the only time the raw key is visible