https://www.geeksforgeeks.org/adding-permission-in-api-django-rest-framework/
https://stackoverflow.com/questions/58904662/django-rest-framework-genericviewset-with-authentication-permission-decorator
APIView is to render API in a HTML view, and has build in authentication, permission and status code for invalid request :
It can be used both in function and in class:
used in fuction :
from django.http import (HttpResponse, HttpResponseRedirect,
HttpResponseServerError)
from rest_framework.decorators import api_view, permission_classes, authentication_classes
# You can use custom authentication class with custom token model, for example in # core/authentication.py
from core import authentication
@api_view(['GET'])
# https://www.django-rest-framework.org/api-guide/authentication/
# Validate header: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
@authentication_classes([authentication.TokenAuthentication])
# Permission to use API
# https://www.django-rest-framework.org/api-guide/permissions/
@permission_classes([permissions.IsAuthenticated])
def function_view(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
used in class :
from django.http import (HttpResponse, HttpResponseRedirect,
HttpResponseServerError)
from rest_framework.decorators import api_view, permission_classes, authentication_classes
# You can use custom authentication class with custom token model, for example in #core/authentication.py
from core import authentication
class ClassBasedView(APIView):
# https://www.django-rest-framework.org/api-guide/authentication/
# Validate header: Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
authentication_classes = (authentication.TokenAuthentication,)
# Permission to use API
# https://www.django-rest-framework.org/api-guide/permissions/
permission_classes = (permissions.IsAuthenticated,)
def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)
No comments:
Post a Comment