API Views Using DRF

Learn via video courses
Topics Covered

Overview

DRF stands for Django REST Framework and which is built on top of Django. APIView class is an important component of the DRF views by which the view class of Django is sub-classed. Rewriting the root view as class-based can be done by the APIView class. Class-based views extend APIViews and determine how the handling of the request can be done and what policy attributes are used by you for the API.

Introduction to DRF Views

Django REST Framework is abbreviated as DRF and the building of which is done on top of Django, so many features are inherited from Django by the DRF. DRF view classes are inherited from the View class of Django. DRF reduces the code amount needed for REST interface creation and provides reusability.

APIView class is an important component of the DRF views by which the view class of Django is sub-classed. APIView class works as the base for all the views selected by you in your application. It can be:

  • function-based views:
    Function can also be used for direct implementation of the APIView. @api_view decorator must be used if view writing is through a function.
  • viewsets:
    Viewset in Django is the combination of the logic of related views.
  • class-based views:
    Alternative approach of implementing views as the objects of Python in place of functions is provided by the class-based views
  • generic view classes:
    Certain Built-in views are combined in the class Based Generic Views which are used for implementing some functionalities such as Retrieve, Create, Delete, and Update.
  • mixins:
    Those classes that commonly inherit from the objects are called mxins

APIView class is used by all above.

Refer to the below image for how APIView is inherited intro-to-api-views-using-drf

Above is the diagram which will show the hierarchy of how different classes are extended by the APIView and Mixins and usability ease increases as we go down in the heirarchy.

So much freedom is provided by the Extending APIView and on the other hand, it also provides a lot of workload. Extending an APIView seems to be a good choice if you need to control all the aspects of the views or if there are complicated views.

The development will be faster through the generic view classes and have a bit of control over the endpoints of API.

API stood up with only five line codes ( two for URLs and three for the view purpose) provided through the ModelViewSets.

Explain How DRF Views Work

When the request comes to the view, firstly request object initialization is done by the view, and the request object is the DRF-enhanced HttpRequest. The following advantages are provided by it in comparison to HttpRequest of the Django:

  • Automatic parsing of content takes place according to the content-type header and it is represented as the request.data.
  • Patch and put methods are supported by it. (only GET and POST are the only methods allowed by Django).
  • Permissions are checked against the other methods of the HTTP on request by temporary method overriding.

After request instance creation, renderers and content negotiators are used by the view for storing accepted information in the request. Authentication is performed by the view after that and permission checking and throttling are performed.

Authentication simply determines the user, any error is not returned by it. Throttle and permissions check needed this information. There is a raising of NotAuthenticated exceptions in case of unsuccessful authentication. And in case the request is not permitted, then there is a raising of PermissionDenied exceptions. And if there is throttling of request at the time of throttling checking then the exception is raised whose name is a Throttled exception.

And there is no notification for the user about the waiting time for the request permission.

check_object_permissions and check_permissions are two parts of permission checking.

General permission is covered by the check_permissions and it is called before the execution of the view handler. check_object_permissions is not executed if APIView is extended you need to explicitly call it for execution. If ViewSets or Generic Views are used then for the detail views there is a calling of check_object_permissions.

The request method is checked by the view of whether it is from one of the given methods below or not. This checking is done after checking the authentication, permissions/Authorization, and throttling.

  • get
  • put
  • post
  • head
  • patch
  • option
  • delete
  • trace

If the request method is one from the above, then it determines whether the method of the request corresponds to any available methods in view and then executes it. A "MethodNotAllowed" error will be displayed if the method is not permitted or specified in the view that is being called.

The APIView class has the dispatch function that is used for checking the method and, according to the name of the method, chooses a handler. Below is the code for the dispatch method which will accept a request as a parameter and check if the request method is available in the list of http_method_names, appropriate handler is created for the method otherwise handler is created for the http_method_not_allowed.

The list of allowed methods is taken from Django instead of defining it in DRF:

The Response object is returned in place of the HttpResponse of Django. The differentiation between the response of DRF and HttpResponse of Django is that initialization of the Response is done with the un-rendered data and rendering of the content is allowed in the various content types, based on the request of the client.

Class-Based Views

APIView class is extended by the Class-based views. It allows the determining of how the handling of the request can be done and what policy attributes are used by you.

For instance, let's assume a model named Student for storing the details of the student:

Now all items deletion at once can be done in the following way. Below is the view created for the deletion of all the items in which first of all we have created a class by extending APIView inside which we are creating a method that will delete all the items available in the object.

For all listing all items of the model, the following view is created

As it is clearly shown that the calling process of the database is completed inside the handler functions. They are chosen based on HTTP method requests (e.g., GET -> get, DELETE -> delete).

As it is shown, the serializer is set in the second view. Complex data( such as QuerySets and model instances) is converted into Native Python data types with the help of serializers. And after this these data types can be rendered into XML, JSON, or any other content type.

Policy Attributes

With the help of policy attributes, default settings can be overridden for the class-based views.

Following are the policy attributes that can be set:

AttributeUsageExamples
renderer_classesIt determines the type of media returned by the response.BrowsableAPIRenderer, JSONRenderer
parser_classesIt determines which data parser is suitable for which media type.FileUploadParser, JSONParser
authentication_classesIt determines which authentication schemas must be used for user identification.SessionAuthentication, TokenAuthentication
throttle_classesIt determines whether the request authorization is done according to the request rate.UserRateThrottle, AnonRateThrottle
permission_classesIt determines whether the user credentials are used for the Authorization of the request.DjangoModelPermissions, IsAuthenticated
content_negotiation_classFor returning to the client, choose one from various resource representations.only custom content negotiation classes

Function-Based Views

APIView can be implemented directly through the function or with the help of the APIView class. @api_view decorator must be used if view writing is through a function.

The main function of the @api_view decorator is to perform the conversion into an APIView subclass ( the response and request classes are provided) from the function-based view.

Allowed methods for the view list are taken by it as an argument.

The working of a function-based view is the same just like that of a class-based view in terms of deleting all available items.

Here, the @api_view decorator is used for performing the conversion of the delete_all_items into an APIView. Methods other than delete are not allowed. The "405 Method Not Allowed" error will be responded to if any other method is used.

Policy Decorators

The Policy decorators can be used for function-based view default settings overriding. One or more than one can be used from the following:

  • @renderer_classes
  • @throttle_classes
  • @authentication_classes
  • @parser_classes
  • @permission_classes

Subclasses of the APIView are corresponded by those decorators.

Conclusion

  • Django REST Framework is abbreviated as DRF.
  • Many features are inherited from Django by the DRF.
  • APIView class is an important component of the DRF views by which the view class of Django is sub-classed.
  • Request method is checked by the view whether it is from one of the given methods below or not. This checking is done after checking the authentication, permissions/Authorization, and throttling.
  • Class-based views allow the determining of how the handling of the request can be done and what policy attributes are used by you.