A Django Rest Framework Guide

·7 min read

A Django Rest Framework Guide

Introduction

It is only common for a front-end part of an application to interact with web services and require data from them when creating an application. The interaction is made possible through an application programming interface (API) that acts as a mediator between the client-side of the application that requests the information, and the web services that provide responses in a data format like JSON, which can be interpreted over a variety of devices and languages. 

This article will guide us on how to precisely build a Rest API as we utilize the Django Rest Framework. Django Rest Framework (DRF) is built on the Django Framework and it is well recommended for web Rest APIs building, due to the flexible and powerful toolkit it provides.  REST which is an acronym for representational state transfer is an architectural software style that stipulates designing and development guidelines of the Wide World Web architecture. 

This tutorial will use the Django Rest Framework to outline a step-by-step guide in creating such an API.

 

Why Django Rest Framework?

Django Rest Framework provides a number of advantages that make it preferable to other frameworks for building APIs. To mention but a few,

  • It enhances usability to developers because of the web browsable API it creates.
  • A developer can customize different utilities like the serializers and viewsets in the framework and still create a fully functional API.
  • Its documentation is comprehensive enough to guide even beginners through every step of creating the API.

 

Development environment setup

To be at par with every step of the article, you are required to have installed Python in your machine. 

Also, install a virtualenv that will create a virtual environment for your project by running the following command on your machine.

pip install virtualenv

 

Guide to creating a Django project

Cd to your terminal and create a new directory for the entire project. Use these commands below:

mkdir DRFproject

cd DRFproject

 

Creating the virtual environment

Now, we create a virtual environment that is necessary whenever you are working on a project. This tool creates an independent python virtual environment for dependencies needed by every project. Having already installed the virtualenv tool, use this command to create a name for your virtual environment.

virtualenv env

The command that follows will activate the virtual environment in Windows OS.

env\Scripts\activate

To make sure you have the virtual environment activated, you should see its name enclosed in brackets like in the image below.

Command line for Django Rest Framework

  

Django setup

While in the DRFproject directory, we will install Django and Django Rest Framework. 

pip install django

pip install djangorestframework

 

Create a Django project which we will name rest using the Django-admin tool provided by Django.

django-admin startproject rest .

The dot . after the project name will help create the project within the same DRFproject folder.

 

Run this following command to apply database migrations to the db.sqlite3 default database.

python manage.py migrate

 

Next, create an app from where the API will be created and managed through the below command. 

python manage.py startapp rest_api

 

We must add the newly created app and the rest framework to the INSTALLED_APPS section in the settings.py file within the rest_api project. Do not forget the trailing comma after the app name to avoid unnecessary future errors. 

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    #own
    'rest_api',

    #third_party
    'rest_framework',
]

 

Creating the Django Rest API

Creating a REST API involves the use of different Django rest framework components including the models, views, and serializers which we will cover soon. 

 

Initializing the model

The models just like in Django is where the table fields of our database will be created. We will create a model called Language that will contain details about different programming languages. Navigate to the rest_api/models.py file and type in the following code.

from django.db import models

# Create your models here.
class Language(models.Model):
    name = models.CharField(max_length=100)
    paradigm = models.CharField(max_length=200)
    author = models.CharField(max_length=100)

    def _str_(self):
        return self.name

The Language model fields are:

  • name: The name of a particular programming language.
  • paradigm: The classification of the language based on its features.
  • author: The founder of the language.

The _str_() method used, displays a default model attribute. The name attribute will be returned in this case.

Run initial migrations to the model so as to synchronize it to the database schema.

python manage.py makemigrations

python manage.py migrate

 

The Django admin page

Django has a built-in admin interface that authorizes administrators and authenticated users to directly work with the defined model objects.

The model will be registered here in the rest_api/admin.py by passing in the model name to the admin.site.register() function.

from django.contrib import admin
from .models import Language
# Register your models here.

class LanguageAdmin(admin.ModelAdmin):
    list = ('name', 'paradigm', 'author')
    
    admin.site.register(Language)

 

Creating a superuser

This user will act as an admin and be able to login into the admin page and manipulate the database objects from there.

python manage.py createsuperuser

This command will prompt you to enter your ‘username, email, password, and password(again) ’.

 

Working with Serializers

A Serializer is a framework that converts the complex querysets and model objects into Python data types. From these native Python data types, JSON, XML data formats are rendered easily to the client. This conversion is referred to as serialization. This framework also performs the reverse through deserialization, where the data is validated and then converted back to a complex format like querysets. Serializers have a similar implementation to Django’s forms. 

Serializers use a serializer class that maps to the Django model. In this case, we will utilize the ModelSerializer class that allows the automatic creation of a serializer class that contains fields corresponding to the Model fields.

It will also create validators for the serializer automatically. By default, the ModelSerializer includes the .create() and .update() implementations so there will be no need to explicitly define them.  

Create a serializers.py file in the rest_api folder and type in the following.

from rest_framework import serializers
from rest_api.models import Language

class LanguageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Language
        fields = '__all__'

The fields attribute will return all the model fields defined.

Where you need to display only specific fields from the model, you can define a tuple of the specific model fields that you require, as the fields attribute.

 

Defining ViewSets

Next, we will create a ViewSet for the API.

A ViewSet is a single class-based view combining the logic for all the related views in the Django REST framework. 

It provides the .list() and .create() actions through which python objects will be retrieved from the database and more objects will be created.

The ViewSet class is preferred to the View class for the following reasons. 

  • We will only be required to define the queryset once, therefore combining logic repetition in one class.
  • The routers we will require to register the views will eliminate the need to set up URL conf explicitly.
  • ViewSets are useful for rapid development, especially when developing large APIs.

We will use the ModelViewSet which provides a default behavior as an existing base class. In the views.py, write this code.

from django.shortcuts import render
from .models import Language
from .serializers import LanguageSerializer
from rest_framework import viewsets
# Create your views here.

class LanguageViewSet(viewsets.ModelViewSet):
    serializer_class = LanguageSerializer
    queryset = Language.objects.all()

Now, register the created viewset as an URL. The URL will return requests from the views when a template is rendered to the browser.

Create a urls.py file in the rest_api folder and add the code below.

from rest_api.views import LanguageViewSet
from rest_framework.routers import DefaultRouter
from rest_api import views

router = DefaultRouter()
router.register(r'languages', views.LanguageViewSet, basename='language')
urlpatterns = router.urls

The router.urls here provides for our API routing. 

 

Finally, let’s include our app’s URLs in the project’s URLs in rest/urls.py. We define an endpoint through which we will access our rest_api app and include its urls.py file as shown below.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('rest_api/', include('rest_api.urls'))
]

 

Running the API

It’s about time we see the API in real-time! 

Type the command below to run the local server from where the API will be created and rendered.

python manage.py runserver

 

If you correctly followed through with the guide and added the code snippets as shown, you should see a browsable API like this displayed on your browser.

API get request

 

Click and follow the link. The browser should display such a page. From here, you can add details to the API fields and POST them to the database.

API Django Rest Framework POST request

 

We can access specific data by adding a specific id endpoint to the URL in the browser to request data of that specific id using the GET method.  Here, we will access the object of id number 2. When it is returned, we can perform operations on it like PUT that can edit the object’s information, or DELETE that will delete the object’s information even in the database.

Django Rest Framework GET and DELETE and PUT

Well, that was quite some fun!

 

Conclusion

The article basically has taught us about what a Rest API is and how we can use the Django rest framework to create a Rest API by implementing the framework’s utilities like the model, the ModelSerializer, and the ModelViewSet

Now you can go ahead and practice more and come up with your own Rest API using this step-by-step guide.

Have fun coding!