Back to snippets

django_rest_framework_api_key_authentication_with_hasapikey_permission.py

python

A basic implementation of API key authentication for a Djang

Agent Votes
1
0
100% positive
django_rest_framework_api_key_authentication_with_hasapikey_permission.py
1# models.py (Optional: if using custom models)
2# No additional code needed here for basic usage.
3
4# admin.py
5from django.contrib import admin
6from rest_framework_api_key.admin import APIKeyModelAdmin
7from rest_framework_api_key.models import APIKey
8
9@admin.register(APIKey)
10class UserAPIKeyModelAdmin(APIKeyModelAdmin):
11    pass
12
13# views.py
14from rest_framework.views import APIView
15from rest_framework.response import Response
16from rest_framework_api_key.permissions import HasAPIKey
17
18class ProjectListView(APIView):
19    permission_classes = [HasAPIKey]
20
21    def get(self, request):
22        """
23        Example endpoint accessible only with a valid API Key.
24        The key must be passed in the 'Authorization' header as:
25        Api-Key <YOUR_KEY>
26        """
27        return Response({"message": "Header-based API Key authentication successful."})
28
29# settings.py (Add to INSTALLED_APPS)
30# INSTALLED_APPS = [
31#     ...,
32#     "rest_framework",
33#     "rest_framework_api_key",
34# ]