Building custom views

REST framework provides an APIView class, which builds API functionality on top of Django's View class. The APIView class differs from View in using REST framework's custom Request and Response objects and handling APIException exceptions to return the appropriate HTTP responses. It also has a built-in authentication and authorization system to manage access to views.

We are going to create a view for users to enroll in courses. Edit the api/views.py file of the courses application and add the following code to it:

from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from ..models import Course

class CourseEnrollView(APIView):
def post(self, request, pk, format=None):
course = get_object_or_404(Course, pk=pk)
course.students.add(request.user)
return Response({'enrolled': True})

The CourseEnrollView view handles user enrollment in courses. The preceding code is as follows:

  1. We create a custom view that subclasses APIView.
  2. We define a post() method for POST actions. No other HTTP method will be allowed for this view.
  3. We expect a pk URL parameter containing the ID of a course. We retrieve the course by the given pk parameter and raise a 404 exception if it's not found.
  4. We add the current user to the students many-to-many relationship of the Course object and return a successful response.

Edit the api/urls.py file and add the following URL pattern for the CourseEnrollView view:

path('courses/<pk>/enroll/',
views.CourseEnrollView.as_view(),
name='course_enroll'),

Theoretically, we could now perform a POST request to enroll the current user in a course. However, we need to be able to identify the user and prevent unauthenticated users from accessing this view. Let's see how API authentication and permissions work.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.204.201