Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and some basic knowledge of REST is a prerequisite. DRF allows the developer to define the URL structure. It includes a built-in API browser for testing newly developed API.

DRF built API is rich in features like a wide range of media type support, authentication and permission policies. For more complex functionality, standard function-based views or granular with powerful class-based views are used.

API

API stands for Application Programming Interface, allows two different applications to communicate, and acts as a mediator. For Web applications, communication takes place over a network or internet. This makes developers easy to certain technologies by providing predefined functionality. The API receives data usually in JSON format from other application and provide to the backend.

RESTful API

REST stands for Representational State Transfer. It is an architecture Web applications are developed on. Web services using REST architecture are called RESTful Web Services. RESTful API acts as a translator between two machines communicating over a Web Service through HTTP. URLs(endpoints) define the structure of API and how a user will access data from an application using HTTP methods like GET, POST, PUT, DELETE. RESTful API returns JSON files that a variety of devices can interpret. Ex., Facebook API, Google API, etc. are REST APIs

Create an API using DRF

Step 1:- Create a Django project and run the following command after moving inside the project directory

python manage.py startapp first_api

Step 2:- Install the Django REST Framework by executing the command below

pip install djangorestframework==3.10

Step 3:- Install rest_framework and basic_api inside the variable name INSTALLED_APPS the settings.py file.

Step 4:- Create models.py

from django.db import models


Rate = [
    ('excellent', 2),
    ('good', 1),
    ('bad',0 )
]


class DRFPost(models.Model):
    name = models.CharField(max_length = 50)
    author = models.CharField(max_length = 50)
    rating = models.CharField(choices = Rate, default = 'good', max_length = 50)


    def __str__(self):
        return self.name

Step 5:- Register model with Django-admin admin.py.

from django.contrib import admin
from first_api.models import DRFPost


# DataFlair
admin.site.register(DRFPost)

Step 6 :- Run server

python manage.py runserver

Step 7:- Create the 3 layers of DRF API

Basic Architecture

The Django REST Framework API consists of 3 layers:

  • Serializer

It converts the information stored in the databases or Django Model instances as complex structures into formats like JSON or XML, which API can easily transmit. Whenever a user submits a piece of information through the API serializer receives that data and then validates it and converts it into a form that can be put into a Model instance. Likewise, when a user accesses a piece of information via API, the instance is fed to the serializer, which parses them into JSON format to the user. The following code is saved as serializer.py in the api directory of the project

from rest_framework import serializer
from first_api.models import DRFPost
class DRFPostSerializer(serializer.ModelSerializer):
    class Meta:
        model = DRFPost
        fields = (‘name’, )

Serializer class is imported from the rest_framework, which is the DRF used.

The serializer class is created, which has model and field attributes. The model will specify the model for the serializer. Fields specify which fields are accessible using the serializer. Instead of field exclude can be set which include all model except the model specified.

  • ViewSets

It is where available operations like Read, Create, Update, Delete are defined via API. The ModelViewSet has the following in-built operations:

  • Create instance – create()
  • Retrieve instance – retrieve()
  • Update instance – update() or partial_update()
  • Destroy instance – destroy()
  • List instance – list()

The following code is saved as views.py in the api directory of the project

from first_api.serializer import DRFPostSerializer
from first_api.models import DRFPost


class DRFViewSet(viewsets.ModelViewSet):
    queryset = DRFPost.objects.all()
    serializer_class = DRFPostSerializer

We will import the model and serializer we created. We created ViewSet class which contains queryset and serialozer_class attributes.  The queryset provides the model instance to operate on. In the serializer_class, we specify the serializer class to create a JSON model.

For customization, we can use generic viewsets, which will provide us with the classes which will make it easy to deal with RESTful requests and send JSON data.

  • Routers

Provides URL that will provide access to each viewsets.

from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from first_api import views




router = routers.DefaultRouter()
router.register(r’drf’, first_api.DRFViewSet)


urlpatterns = [
    path('basic/', views.DRFVieSet.as_view()),
    path('basic/<int:pk>/', views.DRFViewSet.as_view()),
]


urlpatterns = format_suffix_patterns(urlpatterns)

The format_suffix_patters will generalize our urls. The views we created is imported. In view function name of the class is written accompanied by as_view().

Django REST Framework

Advantages of REST Framework

  • Simplicity
  • Flexibility
  • Serialization compatible with ORM and non-ORM data source
  • Easy to customize
  • Classed based Views are cleaner and simpler
  • Pluggable authentication like OAuth1, OAuth2, etc.
  • HTTP response handling
Django REST Framework

Related Topics

Django Framework

Django is a popular high-level open-source web development Python framework based on follows Model View Template (MVT) architecture that allows rapid development. It. It provides common functionality like Admin Interface,...

3 minutes read.

Django Channels

Channels is a project that uses Django and adds some functionalities beyond the traditional HTTP by using WSGI and ASGI.  We can use both synchronous and asynchronous requests with ASGI...

5 minutes read.

Django Forms

Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison. It...

3 minutes read.

Django REST Framework

Django REST Framework (DRF)is an open-source, powerful, and flexible toolkit used to build RESTful web APIs. It is built upon the Django framework. DRF increases the development speed. Django and...

4 minutes read.

Features of Django

Features of Django Offers High Security:- Django is super secure. To prove the feature, we can always take examples of lots of websites which are present worldwide and possess huge traffic. Django is secure because it covers the...

3 minutes read.

Django Filters

Django is a high-level python based web framework. Django is mostly used as a backend engine for websites. Nowadays, every website communicates to a database to fetch all the information...

3 minutes read.

Django Template System

Django Template System Django allows Python and HTML to be divided, the Python goes into views, and HTML goes into templates. Django relies on the render feature and the language of the Django Model...

5 minutes read.

Django vs Laravel

Django Overview Django is a Python Programming Open Source framework for web development. It was released in 2008 and was developed by two web developers named Adrian Holovaty and Simon Willison....

4 minutes read.

Django Create Project

Django is an open-source free to use web framework which is based on Python. Django uses Model-View-Template as its architecture. The final version of Django was released in 2008. Django...

4 minutes read.

Django Messages

Django Framework Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

6 minutes read.

Django Environment Setup

Django is a free and open-source web framework, which uses Python as its programming language. It is based on Model View Template (MVT) architecture. A framework is a collection of...

4 minutes read.

Django – Sending E-mails

Django – Sending E-mails Django comes with a light engine that is ready and simple to use to send emails. Similar to Python, you just need to import a smtplib. You just need to import django.core.mail in Django. Edit the project settings.py file to start sending emails and set  all the following options: EMAIL_HOST – server with smtp.EMAIL_HOST_USER – smtp server login key.EMAIL_HOST_PASSWORD ? Password credential for the smtp server.EMAIL_PORT – server port smtp.EMAIL_USE_TLS or _SSL – if it is secure connection then set True. Simple E-mail Sending To submit a simple e-mail, let's create it a "simpleEmail" view. from django.core.mail import...

3 minutes read.

Life Cycle of Django

Life Cycle of Django Request - Response life cycle in Django  Thebasic principle of http protocol is the client sends a request to the server based on the request data, and the server sends...

3 minutes read.

How to Implement Multiple User Types with Django

Django Framework: Django is a framework that can make web applications more accessible and faster. Django is an open-source collection of python libraries, and Django can be used for both the...

3 minutes read.

How to create an app in Django

Create an application in Django Django is famous for its unique and fully managed application structure. For each functionality, an application can be created as a completely independent module. This article will take...

2 minutes read.

Django MVT

 MVT(Model View Template) MVT means Model View Template is a software design pattern The View is used to implement the business logic and to communicate with a model for data transmission and to...

2 minutes read.

Django CMS

Django is one of the most popular open-source Python web development framework. Developers use Django to build a website from scratch. Like WordPress, Django CMS is also a Content Management...

9 minutes read.

Django Pagination

Django is an open-source free to use python based web framework. Django provides many inbuilt tools for web developers to provide rapid web development. One of these tools is pagination....

4 minutes read.

Django All Auth

For any web application, user registration and authentication are the essential parts. In Django, there are several applications like django-registration-redux to perform these tasks, but the major drawback is that...

6 minutes read.

Uses of Django

Django is a free and open-source Python-based web framework, which offers great functionalities to its users. Django was developed in 2003, and the final version was released in 2008 by...

3 minutes read.