Django REST Framework Tutorial – Feel Blessed!! ‘Coz Boss wants you to REST
We will learn to build a REST API in Django through a very simple method. Just follow the below steps and your first API will be ready to get going with minimum code.
Django REST Framework (DRF) allows developers to rapidly build RESTful APIs. We will see how DRF is actually used and also clear some very basics of the web. This article assumes though, that you have a basic understanding of the working of the web. We will learn topics like Django for APIs, RESTful web services and then build up to DRF.
Okay, so buckle up for this article.
Keeping you updated with latest technology trends, Join DataFlair on Telegram
What is an API?
Before understanding what DRF can do we first need to understand what is an API. API is an acronym for Application Programming Interface. Two machines use it to communicate with each other. We will be dealing with Web APIs and then the definition changes to:
An API is used by two applications trying to communicate with each other over a network or Internet.
With this definition in mind, let’s look at a block diagram.
The above figure helps in visualizing the working of an API. The API acts as a mediator between Django and other applications. As you can see, other applications can be from Android, iOS, Web apps, browsers, etc. The API’s main task is to receive data from other applications and provide them to the backend. This data is usually in JSON format.
Okay, so some of you may ask what about those so-called Google APIs. Okay, let’s see. They are also APIs of the same nature. Understand it like Google providing the API as a service.
Here, you can see some of the common examples of APIs used by developers.
This is the link of Google geocoding API used to insert the functionality of Google Maps on your website. This is one of the many examples. Not just Google but many companies provide their APIs as a service. These services are used by the developers to provide maps service to end-users. There is nothing different for these APIs and the ones we discussed earlier. These APIs do the same thing, they simply transfer data from our application to the Google server. The server then returns the response through this very same API. That response is then passed by our server to the end-user. Sometimes, this can be bypassed to directly give a response to the end-user.
APIs are programs that exist to transfer data between applications. They are responsible for cleaning and formatting data correctly.
What are RESTful APIs?
Well, first we need to understand what is REST. Don’t worry, I will explain it in simple words.
REST stands for Representational State Transfer. REST is an architecture on which we develop web services. Web services can be understood as your device connects to the internet. When you search for anything on Google or watch something on YouTube. These are web services where your device is communicating to a server. When these web services use REST Architecture, they are called RESTful Web Services. These web services use HTTP to transmit data between machines. now, back to the question, what are RESTful APIs?
A RESTful API acts as a translator between two machines communicating over a Web service. This is just like an API but it’s working on a RESTful Web service. Web developers program REST API such that server can receive data from applications. These applications can be web-apps, Android/iOS apps, etc. RESTful APIs today return JSON files which can be interpreted by a variety of devices.
The RESTful API will provide standardized data to all devices. Currently, that is achieved by JSON format but REST is not limited to that. Okay, for the last part JSON, we will see it in further sections.
One last question to be answered.
What is Django REST Framework?
So, as we learned in previous sections, DRF is an acronym for Django REST Framework. (stating the obvious) It’s used to develop REST APIs for Django. Yup, DRF is used to develop RESTful APIs which is both easy and a smart way.
DRF is a framework built upon the Django Framework. It is not a separate framework. You can say that it is a tool which alongside Django is used to develop RESTful APIs. It increases the development speed. It also addresses various security issues natively. DRF is an Open Source Software, just like Django. It is actively developed by various MNCs. If you made any profit from this framework then please donate it to keep it open source.
The documentation of DRF is actually considered better than Django’s. The only catch is that you need to have a bit of previous knowledge to understand the DRF documentation. Django is, of course, the prerequisite but also some basic knowledge of REST is necessary.
Also, we will discuss various features of the Django Rest Framework alongside.
Note: All the code for this article is in this repository:
Making a basic_api with DRF
Let’s start by making a new django-project. In your virtual environment, make a new project DRFtutorial. We will develop a simple API to understand what is done by DRF.
django-admin startproject DRFtutorial
When you make the project just move inside the DRFtutorial directory. Then run
python manage.py startapp basic_api
The basic_api is created. Now, we also need to install Django REST Framework. To install it, execute this command.
pip install djangorestframework==3.10
Now, open settings.py file of your project. There install these two apps, ‘rest_framework’ & ‘basic_api’. Just include them in the INSTALLED_APPS list.
Now, paste this code of model in basic_api/models.py file.
# basic_api/models.py from django.db import models #list Grade = [ ('excellent', 1), ('average', 0), ('bad', -1) ] # DataFlair class DRFPost(models.Model): name = models.CharField(max_length = 100) author = models.CharField(max_length = 100) uploaded = models.DateTimeField(auto_now_add = True) rating = models.CharField(choices = Grade, default = 'average', max_length = 50) class Meta: ordering = ['uploaded'] def __str__(self): return self.name
Also, register this model with django-admin. Add this code to basic_api/admin.py file.
from django.contrib import admin from basic_api.models import DRFPost # DataFlair admin.site.register(DRFPost)
Ok, now we need to migrate our changes in the database. Execute these two commands in the terminal.
python manage.py makemigrations python manage.py migrate
Now, we can use the admin to populate our database. Also, before that please create a superuser. You can create a superuser by executing the following command.
python manage.py createsuperuser
Fill in your details which prompts you and then you should get something similar to this image.
Start your server and populate your database with the use of Django-admin.
python manage.py runserver
Then open URL: localhost:8000/admin
After that, log in with your superuser credentials. Then add some records in the basic_api app.
After that, our first part of DRF comes into play.
We developed our models in the previous section. In this section, we will develop serializers. Let’s understand what are these serializers used for.
Serializers are used to transform our model instances or objects into JSON.
You can say it’s similar to the Python dictionary. It’s just a file that is sent/ received by the API to various applications. That’s what serializers help us do here.
Serializers are an important part of DRF. We will be using serializers to get the JSON files for our models. It’s not easy to implement with just Django. Serializers can easily create JSON responses from our model instances. This is one of the magical things DRF can perform.
To implement serializers in our project, create a new file in the basic_api directory called serializers.py. Then paste this code in the file basic_api/serializers.py:
from rest_framework import serializers from basic_api.models import DRFPost class DRFPostSerializer(serializers.ModelSerializer): class Meta: model = DRFPost fields = '__all__'
Understand the code:
Let’s understand what we just did. We created a new file serializers.py in our application. This file contains the code similar to modelforms code.
We imported the serializer class from the rest_framework module. This is the DRF used in Django. They couldn’t use Django as it would conflict with the existing name itself. Then we imported the model we wanted serializer for. Then like model forms class, we created serializer class. This is called the model serializer class.
The model serializer class will take the model attribute and field attribute.
The model attribute will input the model for the serializer. The fields attribute takes a list containing the names of fields. These are the fields which will be passed as a json file.
Now, we will also need views and urls to see how all this works.
We are going to use class_based views here. This is different from function-based views.
In basic_api/views.py file, paste this code:
from django.shortcuts import render from rest_framework import generics from basic_api.models import DRFPost from basic_api.serializers import DRFPostSerializer class API_objects(generics.ListCreateAPIView): queryset = DRFPost.objects.all() serializer_class = DRFPostSerializer class API_objects_details(generics.RetrieveUpdateDestroyAPIView): queryset = DRFPost.objects.all() serializer_class = DRFPostSerializer
Understand the code:
The views written here are simply CBVs or class-based views. Also, they are not simple CBVs but DRFs generic class’s CBVs.
In the first 4 lines, we are importing all the important things we are going to need in view. We imported models, serializer class and generics class. The generics class will provide us with the web browsable API. The generics class is a special class in rest_framework. There are also generic views for Django itself. They are for a different purpose.
You need to keep it in mind that this is an API. It’s not meant to be displayed to the user. It’s for programs or applications communication. The generics class will provide us with important classes. These classes make it easy to deal with RESTful requests and send JSON data.
This means that this is the serializer model to be used to create a JSON model. The view part will handle the calling of correct classes and queries. It will then respond with the JSON response to the client or other application.
The second view class is also similar to the 1st. I discussed earlier; this view logics are not needed to be known. You should know what results we get. You do not need to reinvent the wheel or have an understanding of the whole framework. The second class will provide details of an individual object.
There are more operations that can be performed on an individual object. Therefore, we are using class generics.RetrieveUpdateDestroyAPIView class. This class will provide Read, Update and Delete Functions on the model instance. Ok, now let’s set up the urls.
Now, create a new file as basic_api/urls.py. This is urls for the basic_api app. Paste this code in the basic_api/urls.py file.
# basic_api/urls.py from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from basic_api import views urlpatterns = [ path('basic/', views.API_objects.as_view()), path('basic/<int:pk>/', views.API_objects_details.as_view()), ] urlpatterns = format_suffix_patterns(urlpatterns)
Understanding the code:
In this code, we have created a urls.py file. There are some new terms here though. The new import is from rest_framework.urlpatterns. The format_suffix_patterns method will be used to generalize our urls. It will make the urls to work with URIs like
http://basic/4 and http://basic/4.json
Both of these urls can be handled by our web app. Then we imported the views from the basic_api app. After that, we simply defined the urls.
The new part is the view function we have written. This is what you call a view from a Class-Based Views in Django. In the view functions, we write the name of the class. The class name is always accompanied by the as_view() method. This is true for all CBVs out there and is not limited to DRF.
That’s it. After that the format_sufix_patterns() is used on urlpatterns.
Configuring main urls.py file
Paste these lines of code in the DRFtutorial/urls.py file.
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('basic_api.urls')) ]
The setup is now complete. Save your changes and again reload the server.
After you have reloaded the server, open this URL: http://localhost:8000/basic/
It will come up with this output.
From the urls.py file, you can easily say that this is the list of objects.
The code you can see in square braces  is the actual JSON output. I told you earlier, JSON looks very similar to Dictionaries in Python.
JSON is simply a format which is used as a standard for data interchange. It is lightweight and therefore, takes in less bandwidth.
A simple JSON object from our example is:
Here the keys are strings and values can be strings or other data-structures. The values can be objects too. JSON is beginner-friendly and easy to use.
The id is key and 1 is value. That is the formatted data that applications can use to extract information. Structured information is always favored.
Now, your search for this URL: http://localhost:8000/basic/2/
This is the output rendered by the browser. The 2 in the URL is the id of the object. It is a specialty of Django to automatically attach id attribute to models. Notice, now we are getting only one object. That object has id = 2.
You can see, the first output was a list of objects. The second output is a single object. Also, at the bottom of the page, there is an HTML form. This form is used to modify the current object. If you modify and click on the PUT button, then the object information will change.
You can also delete objects by clicking on the delete button.
What’s DRF doing here?
Many would ask at this time that what’s the role of DRF. All this could have been achieved by Django Admin if I wanted to perform CRUD operations. Well, it is true. The point is DRF is for applications. The DRF has this special feature of browsable API. Otherwise, you would have seen just the JSON response like this.
DRF makes it easier for a developer to debug their APIs. The other big feature of DRF is that it converts the Models into serializers. What we have done in this Django REST Framework tutorial is simply made classes and extended them with built-in classes. If we needed to have this kind of architecture, we would need so much more code in place. DRF made it so easy for us to serialize data.
The serializers not only take our models and transmit them as JSON objects. They also provide data from users to the backend. They automatically clean the data or validate data. This is a plus from DRF. Cleaned data removes all the security issues.
Believe me, the security provided by DRF is well established. Django REST Framework has many more features than explained here. They go well beyond the scope of just Django. You will need a better understanding of APIs and REST architecture. It is not so difficult but will take time.
We can say that DRF is an amazing extension to Django. Django is capable on its own but DRF takes that one step ahead. Django’s rapid development is boosted by the use of DRF. Django Rest Framework has more features like Requests and response methods. There is so much DRF is capable of and the same goes for all readers. DRF will let you communicate with various applications over the internet. The most prominent Django REST Framework examples are of Android Applications and Web apps. You will only have different UI/ Ux. The backend will be Django. API communication is handled by Django REST Framework. That’s how you can do full-stack development.
Freely mention your queries regarding the DRF tutorial in the comment section.