Last modified: Sep 20, 2023 By Alexander Williams
Django Rest Framework's APIView: Examples and Usage
Creating a Basic APIView:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class MyAPIView(APIView):
def get(self, request):
data = {'message': 'Hello, APIView!'}
return Response(data, status=status.HTTP_200_OK)
Output:
{"message": "Hello, APIView!"}
2. Handling POST Requests:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class MyAPIView(APIView):
def post(self, request):
# Handle POST data and perform actions
data = {'message': 'POST request received successfully'}
return Response(data, status=status.HTTP_201_CREATED)
Output:
{"message": "POST request received successfully"}
3. Handling URL Parameters:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class MyAPIView(APIView):
def get(self, request, pk):
# Use 'pk' to fetch data related to a specific resource
data = {'resource_id': pk, 'message': 'Resource details fetched successfully'}
return Response(data, status=status.HTTP_200_OK)
Output:
{"resource_id": "1", "message": "Resource details fetched successfully"}
4. Handling PUT and DELETE Requests:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class MyAPIView(APIView):
def put(self, request, pk):
# Handle PUT request to update a resource
data = {'message': f'Resource {pk} updated successfully'}
return Response(data, status=status.HTTP_200_OK)
def delete(self, request, pk):
# Handle DELETE request to delete a resource
data = {'message': f'Resource {pk} deleted successfully'}
return Response(data, status=status.HTTP_204_NO_CONTENT)
Output (PUT Request):
{"message": "Resource 1 updated successfully"}
Output (DELETE Request):
{"message": "Resource 1 deleted successfully"}
Authentication and Permissions:
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.authentication import TokenAuthentication
class MySecuredAPIView(APIView):
authentication_classes = [TokenAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
data = {'message': 'Authenticated and authorized access'}
return Response(data, status=status.HTTP_200_OK)
Output:
{"message": "Authenticated and authorized access"}