You can use django rest framework
permission classes to check request headers and authenticate user requests
Define your secret_key on project settings
API_KEY_SECRET = 'secret_value'
note: a good practice is to use environment variables to store this secret value.
create permissions.py file on your app dir with below codes:
from django.conf import settings
from rest_framework.permissions import BasePermission
class Check_API_KEY_Auth(BasePermission):
def has_permission(self, request, view):
# API_KEY should be in request headers to authenticate requests
api_key_secret = request.META.get('API_KEY')
return api_key_secret == settings.API_KEY_SECRET
from rest_framework.response import Response
from rest_framework.views import APIView
from .permissions import Check_API_KEY_Auth
class ExampleView(APIView):
permission_classes = (Check_API_KEY_Auth,)
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.response import Response
from .permissions import Check_API_KEY_Auth
@api_view(['GET'])
@permission_classes((Check_API_KEY_Auth, ))
def example_view(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)