...

/

Creating the Houses and Checkers Views for REST API CRUD

Creating the Houses and Checkers Views for REST API CRUD

Learn how to create views in the Django application.

Handling views in Django

Before we create our House and Checker views, let’s take a moment to learn about views in Django. In web-based applications, views are responsible for handling HTTP requests and returning the appropriate response. They handle how the response data is delivered to users for viewing and consumption. The response from a view can be in any form: a media file (an image or video), HTML content, an error status code, an entire web page, a redirect message, etc. For RESTful APIs, this response can be in JSON or XML data formats.

Unlike in web development, where we have the Model-View-Controller (MVC) architecture, we use the Model-View-Template (MVT) in Django. Here, the view is the controller that decides the data sent to the template, while the Django template corresponds to the views in the MVC architecture. A view obtains data from our database or outside sources and sends it to the template.

In Django, we have class-based views and function-based views. When a view is created as a function that returns a web response after implementing the necessary business logic, it is known as a function-based view. In contrast, a class-based view is created from inherited classes. However, when developing APIs with the Django REST framework, we are provided with two useful choices for handling our views: APIView and ViewSet. These are simple but powerful tools to speed up our RESTful API development and CRUD actions execution. We'll use them in this lesson.  

Creating the House view

To create our House view, open houses/views.py. We'll see the view creation boilerplate that imports the render module:

from django.shortcuts import render

# Create your views here.

We'll use ViewSet to create our House view. We'll clear the first line and import the viewsets module from the rest_framework. We'll also import status and Response from the rest_framework. Then, we'll import our House and Checker models and the HouseSerializer from their respective files in our ... ...