Building an API


Recap: Django Rest Framework

Django is a great Python framework for building web applications.

One of its most important features is its templating system, with which the web application renders an HTML response.

Recall that an API returns a JSON or XML response to any client that consumes it.

However, the core Django framework is not suitable for this purpose.

The Django REST Framework (DRF) acts as a wrapper around the core Django library. It serializes the view response into JSON format and returns it to the client.

Recall that the process of serialization involves converting the model instances to native Python datatypes so that they can be rendered into JSON format.

Deserialization parses the data back into the model instance after first validating the incoming data.

DRF provides a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.

To build a REST API with Django, you need to install the Django REST Framework in the same environment in which Django core is already present.

You can install the Django REST Framework with the following command:

pip3 install djangorestframework

First steps

Let us quickly recap the steps to create a Django project and an app:

(workspace) C:\workspace>django-admin startproject demoproject . 
(workspace) C:\workspace>cd demoproject 
(workspace) C:\workspace>django-admin startapp demoapp 
(workspace) C:\workspace>cd.. 
(workspace) C:\workspace>python manage.py migrate 
(workspace) C:\workspace>python manage.py createsuperuser 
(workspace) C:\workspace>python manage.py runserver 

The steps from the code snippet above create a Django project called Demoproject and, inside it, an app called Demoapp.

They also build the database structure for the pre-installed apps, create a super user, and run the server.

Once you create the superuser, you can log into the Django administration interface using those credentials.

Next, make sure that you update the INSTALLED_APPS list by adding 'rest_framework' to it inside the settings.py file.

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Serializer class

The next step is to build a RESTful API to work with the User model defined in the pre-installed django.contrib.auth app. First, you declare a UserSerializer class to serialze the User model instance.

from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']

Use the ModelSerializer as the base for the class. You need to set the model attribute of its Meta subclass to User and specify the fields to be exposed via the API.

Views

Next, we define the views for our app. DRF views can be of any of the following types:

  • function-based views
  • class-based views
  • mixins
  • generic view classes
  • viewsets

Viewset class

Open the views.py file in the demoapp package folder and UserViewSet class.

The permission_classes attributein the ViewSet class is set to the IsAuthenticated class. This makes the unauthentictated user unable to access this view.

The Django REST Framework supports function based views too. You must provide separate views for each method such as GET, POST, PUT and DELETE. Views based on generic ViewSets are concise. It makes the logic more organized.

To refresh your understanding, please visit the following link:

Generic views and ViewSets in DRF

URL Configuration

To wire up the API URLs, you can use the DefaultRouter class instead of declaring URL routes in the app and then including it in the project’s URLConf.

router = routers.DefaultRouter()  
router.register(r'users', views.UserViewSet)  
 
urlpatterns = [  
 
    path('', include(router.urls)),  
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))  

The api-auth route is defined to let you use the browsable API feature of DRF.

Browsable API

Now that the code is ready, you can run the server if it is not already running and visit the URL for browsable API in the browser.

You can test the API from inside the browser itself and notice that the superuser you created in the beginning displays.

As an additional task, try and use the POST window to create another user.

In this Reading, you learned how to develop a basic API using the Django REST Framework.


Exercise: Set up the menu API

Overview

In previous exercises, you have already set up a LittleLemon project that includes the Restaurant app. You have also declared the Menu and Booking models, migrated to the MySQL database.

In this exercise, you will build a REST API to perform CREATE, READ, UPDATE AND DELETE operations on the Menu model

Scenario

You will use Django REST Framework to build the APIs in the restaurant app. You will also create the views using DRF’s generic views.

Step 1

Install the ‘rest_framework’ with PIP utility while remaining in the Django virtual environment directory.

Open the command prompt in the LittleLemon directory and start VS Code.

Step 2

Open the settings.py file and add 'rest_framework' in the LittleLemon project’s INSTALLED_APPS list.

Step 3

The Serializer in Django REST Framework converts compound data types into JSON or XML format. ModelSerializer is a special type of serializer that quickly creates a serializer class from the Django model fields.

The ModelSerializer class is declared in the rest_framework.serializers module.

In the app package folder, create a new file called serializers.py and declare the MenuSerializer class that subclasses ModelSerializer.

Step 4

Open the views.py module in the restaurant app package folder.

Declare two classes:

  1. MenuItemView – inheriting the rest_framework.generics.ListCreateView class. It handles the POST and GET method calls.
  2. SingleMenuItemView – inherits the RetrieveUpdateAPIView and DestroyAPIView classes both imported from the rest_framework.generics module. This class is responsible for processing GET, PUT and DELETE method calls.

Step 5

Define URL routes for the restaurant app’s menu views in the urls.py file.

#add following lines to urlpatterns list 
path('menu/', views.MenuItemsView.as_view()),
path('menu/<int:pk>', views.SingleMenuItemView.as_view()),

Include app URLs in the LittleLemon project’s urls.py module.

#add following line to urlpatterns list 
path('restaurant/menu/',include(restaurant.urls'))  

Step 6

Run Django server, and open the URL http://localhost:8000/restaurant/menu/items.

This is the URL of the browsable API. Perform POST operations to add menu items. With the GET request, fetch the list of items.

Tips

Use the following code snippet to declare the serializer class:

#define Serializer class for User model
from django.contrib.auth.models import User 
from rest_framework import serializers 
 
class UserSerializer(serializers.ModelSerializer): 
 
    class Meta: 
        model = User 
        fields = ['url', 'username', 'email', 'groups']

You can use the following code snippet to define views:

from rest_framework.decorators import api_view
from .models import MenuItem
from .serializers import MenuItemSerializer
 
# Create your views here. 
class MenuItemsView(generics.ListCreateAPIView): 
queryset = MenuItem.objects.all() 
serializer_class = MenuItemSerializer
 
class SingleMenuItemView(generics.RetrieveUpdateAPIView, generics.DestroyAPIView):     
queryset = MenuItem.objects.all() 
serializer_class = MenuItemSerializer

Conclusion

In this exercise, you have used Django REST framework to set up the Menu API for the Restaurant app.


Exercise: Set up the table booking API

Overview

So far, you have built a Menu API in the Restaurant app of your Django project with the name LittleLemon

In this exercise, you will add a Table booking API in the restaurant app. The booking model is already declared and migrated.

Scenario

While building the table booking API, you will define a class-based view with Django REST Framework’s ModelViewSet class. Declare the view class as BookingViewSet.

You will also use the DefaultRouter class to register the URL routes.

Steps

Step 1

Open the project in VS Code. Ensure that 'rest_framework' is added in the INSTALLED_APPS list.

Step 2

In the serializers.py file present in the app folder, declare the BookingSerializer class. Use the ModelSerializer as its base. Set the model attribute to booking, and fields to __all__.

Step 3

In the app’s views module, declare the BookingViewSet class, inheriting the rest_framework.viewsets.ModelViewSet class.

Fetch all the objects from the booking model. Set the serializer_class attribute to BookingSerializer.

Step 4

Open the urls.py file in the LittleLemon project package (not the restaurant app package folder).

Import the rest_framework.routers.DefaultRouter class. Call its register method to wire up the 'booking' URL route with the BookingViewSet class.

router.register(r'tables', views.BookingViewSet)

Add this router in the project’s URL patterns.

urlpatterns = [
path('restaurant/booking/', include(router.urls)),
]

Step 5

Visit the browsable API URL http://localhost:8000/restaurant/booking/tables. You can perform table booking operations in the browser window.

Tips:

To declare the ViewSet class, you can use the following example:

class UserViewSet(viewsets.ModelViewSet):
   queryset = User.objects.all() 
   serializer_class = UserSerializer
   permission_classes = [permissions.IsAuthenticated] 

Conclusion

In this exercise session, you built a table booking API with Django REST Framework.


Additional Resources

Here is a list of resources that may be helpful as you continue your learning journey. These resources provide some more in-depth information on the topics covered in this module.

Django REST framework

APIs


APIDjangoDRFPython

Previous one 4.Models and stored procedures | Next one 6.User Authentication