P4 – Django Rest – Class Based Views

In the previous tutorial we have seen how to create rest api and add GET, POST request using independent functions. Now we will see how to create class based views. So with a class based views we can have more separation of concerns of different parts of our application wrapped within a class serving different http requests.

Step 1

It is very simple and aimed at reducing and creating reusable code. Lets create model having seller information as below in the models.py file.


Step 2

Now create a serializer class for the Seller class in the serializer.py file as below


Step 3

Now in the views.py file we define a new class “SellerView” which extends it self from the APIView class. The APIView class is a wrapper class which provided additional standard handling of the various http requests thus abstracting us from the finer details and we can write our functionality faster and in an efficient way. Notice that we have created two methods, one for GET request and one for POST request. The framework will automatically invoke respective methods based on the HttpRequest.

Ignore the additional imports for generics and mixins, we will need them later, we can ignore them for now.

Also note that we have used the format variable and set it None, it means that the function can handle multiple formats. Res t of the code is pretty standard that we have seen in earlier tutorials

Step 4

Now we need to map url pattern to this new Seller class view. See below screenshot where we have added the seller url pattern, we need to pass the as_view return unlike functions itself that we passed earlier with function based views and its done.

Step 5

Its time to test. Lets open the ARC and add one new seller to the rest service and then retrieve it back.

Add new seller to the service
Retrieve the seller back

GIT Project link – https://github.com/letsblogcontent/SampleRestProject

Create your website with WordPress.com
Get started