Django is a Python Web-based Framework that is free and open-source, and it uses the Model–Template–Views design paradigm. Its upkeep is the responsibility of the Django Software Foundation, a non-profit organization based in the United States.

  1. Key Features of Django
  2. Introduction to REST API
  3. REST API Request
  4. Django REST Framework
  5. REST API Using Django REST Framework
  6. Main Advantages of REST Framework

Key Features of Django

Secure

Django’s purpose is to “Do the Right Things” automatically to secure the website. Django avoids common issues such as storing session information in cookies, which is a security risk. In addition, Django protects against SQL injection, cross-site scripting, cross-site request forgery, and clickjacking by default.

Scalable

Django has a “Shared-Nothing” architecture, which means that each architecture component is independent of the others. Because the various components are separated, it may be scaled to meet increased demand by adding hardware at any level.

Maintainable

Django programming is written with design concepts and patterns in mind, resulting in simple code to maintain and reuse. In addition, it applies the “Don’t Repeat Yourself” (DRY) principle to avoid unnecessary repetition and hence reduce the amount of code.

Versatile

Django may be used to build almost any type of website, from content management systems and wikis to social networks and news sites. It can interact with any client-side framework and serve data in almost any format (HTML, RSS feeds, JSON, XML).

Portable

Django is written in Python, a cross-platform programming language. That means the user is not tied to a single server platform and can execute the application Windows, Linux, and Mac OS X.
Django is also well-supported by a significant number of web hosting providers, which frequently provide specialized infrastructure and documentation for hosting Django sites.

Introduction to REST API

The term REST APIs stands for Representational State Transfer Application Programming Interface. A REST API is a data source frontend that allows users to create, update, and delete data items.

A RESTful API, commonly known as REST API, is used to create interactive applications and Web services. This application programming interface uses the constraints of representational state transfer. Representational state transfer, known as REST, is a type of software architectural style that uses a subset of HTTP. A computer scientist named Roy Fielding created RES to determine the exact look of an API. Every URL in REST is known as a request or the API endpoint. Similarly, the information obtained through that request is known as a response.

Building Rest API with Django Rest Framework

REST API Request

A few options are available for the developers working with REST API requests to manipulate the working data. Following are some key options useful for data manipulation:

GET Request

This type of request returns data from the API based on the requested URL. It will return the data present at that particular path.

POST Request

This option puts the provided data at the given URL/API endpoint. Commonly, the endpoint receives the new data and appends it to the previous records in the server database.

PUT Request

The developers use this request type to update the records in a database. If the provided data matches an already existing record, the record in the database gets updated. On the other hand, if there is no matching record for the data, it creates a new record for it depending on the developed API.

DELETE Request

This option simply deletes the required record from the API.

PATCH Request

The developers use this request option to update an individual field in a particular record in the database.

Django REST Framework

The Django REST framework is famous for creating Web APIs. It is a powerful and flexible toolkit built on the Django web framework. The purpose of using this Django REST framework (DRF) is to increase code usability while working with REST interface creation.

Features of DRF

Using the Django REST framework is helpful in many terms, such as it provides usability advantages due to its browsable Web API. The Authentication policies of DRF include specified configurations of servers like Apache; there are authentications for tokens, sessions, and remote users. Moreover, there exist third-party authentications and packages for OAuth1a and OAuth2.

The process of serialization, which helps in converting tabular database values into JSON or any other format, supports both Object Relational Mapping (ORM) and non-ORM data sources. There is also the option to customize the complete framework to avoid using more advanced features. Finally, the developers can elaborate documentation provided by DRF, and community support is there to help enthusiastic developers. Also, the DRF holds a license from many globally recognized organizations such as Mozilla, Red Hat, Heroku, and Eventbrite.

REST API Using Django REST Framework

Django makes the sterilization process easy so the developers do not have to work on low-level implementations. The Django ORM takes care of the most work itself. Following are the steps to create a REST API using Django:

  1. Setting Up Django
  2. Creating a Model for Django ORM
  3. Setting Up Django REST Framework
  4. Sterilizing the Model
  5. Creating the URI endpoints

Setting Up Django

First of all, the users need to install the Django framework on the device. Following is the code to install Django:

$ pip install django

Following is the code to start a new project in Django:

$ Django-admin startproject myproject

This code creates a folder named myproject in the directory. This folder contains all the files needed to run the project. The manage.py file helps running the server. The developers can use the following code for test running the server.

$ python manage.py runserver

The above code gives information about the local host where the server is running. Moreover, it is a good practice to build the Django project in separate applications. The developers can use the following code to create an API for the created project in Django:

$ python manage.py startapp testapi

$ ls

Db.sqlite3 manage.py* testapi/ myproject/

After this, there is a need to register the testapi with myproject for its recognition. Therefore, the developers can make the following edit in the myproject/settings.py file:

INSTALLED_APPS=[
            ‘testapi.apps.TestapiConfig’,
            … # information of other installed apps is given here
]

Furthermore, after implementing the above steps, the user needs to migrate the built-in models into the user’s database to use the database correctly and utilize ORM features. Django automatically creates this SQLite database since the user did not specifically create one. Following is the code used for such migration:

$ python manage.py migrate

Finally, there is a need to create a superuser to access the admin interface. After creating a superuser, the user can assign the admin and administrator roles to the team members using the admin interface. Following is the command to create a superuser in Django:

$ python manage.py createsuperuser

The login credentials will be specified using username, email, and password. The users can also test it by navigating to the localhost provided and putting credentials required to log into it, and the system will display the dashboard for the superuser.

Creating A Model for Django ORM

The developers have to build the model for the database in the testapi/models.py file. Following code is used to create a model for superheroes where each hero possesses a name and an alias. Moreover, the __str__ method tells Django the information to print when there is a need to print the Hero Model instance.


# models.py
from Django.db import models
class Hero(models.Model):
            name=models.CharField(max_length=60)
            alias=models.CharField(max-length=60)
def __str__(self):
            return self.name

Now the changes made for the model previously are migrated using the following code:

$ python manage.py makemigrations
migrations for ‘testapi’:
            testapi/migrations/0001_initial.py
-Create model Hero
$python manage.py migrate

After this, the users have to register the Hero model with the admin site. For this, they need to edit the testapi/admin,py file in the following way:

from Django.contrib import admin
from .models import Hero
admin.site.register(Hero)

The above script will add the model to the dashboard of the superuser. Moreover, the users can create more models like Hero using the Add option on the dashboard.

Setting Up Django REST Framework

The users can install the Django REST Framework can using the following command:

$ pip install djangorestframework

Moreover, the users can edit the information regarding DRF installation in the testapi/settigs.py file:

INSTALLED_APPS=[
            # Every installed app
            …
            ‘rest_framework’,
]

Sterilizing the Model

After installation, there is a need to specify the Hero model and its sterilization to the REST Framework. The users can determine which fields he has to include in the JSON representation of the model using a serializer. The serializer turns the model into JSON representation for the API user to parse it without using Python.

Similarly, the serializer converts the JSON data in the POST request to the model representation of the API. It does the conversion for the storage and validation of data. Therefore, the users need to create a new file named testapi/serialzers.py for these purposes. This file helps import the Hero model, import the REST Framework serializer, and create a new class linking the Hero with the serializer.

# serializer.py
from rest_framework import serializers
from .models import Hero
class HeroSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                        model=Hero
                        fields=(‘name’, ‘alias’)

Creating the URI Endpoints

Finally, the last step is to wire up URLs and create a View for the data. The user needs to render the different heroes in JSON format for the view. They can do it by querying the database for all heroes and passing the query set to the serializer for the conversion into JSON. For this, the users can edit the following  in the testapi/views.py file:

# views.py
from rest-framework import viewsets
from .serializers import HeroSerializer
from .models import Hero
class HeroViewSet(viewsets.ModelViewSet):
            queryset=Hero.Objects.all().order_by(‘name’)
            serializer_class=HeroSerializer

The ModelViewSet handles all the GET and POST for Heroes itself. Finally, the users have to point a URL at the created viewset. They can add the URL for the API in the myproject/urls.py, where they resolve the project’s URLs.

# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns=[
            path (‘admin/’, admin.site.urls),
            path (‘ ‘, include(testapi.urls’)),
]

The testapi.urls is a path to a file that Django will use for the instructions to route the URL. So, it needs to be edited first. Therefore, the following changes are made in the testapi/urls.py file:

# testapi/urls.py
frpm django.urls import include, path
from rest_framework import routers
from . import views
router=routers.DefaultRouter()
router.register(r’heroes’, views.HeroViewSet)
urlpatterns=[
            path(‘ ‘, include(router.urls)),
            path(‘api-auth/’, include(‘rest_framework.urls’, namespace=’rest_framework’))
]

By following the above instructions, the users can successfully create an API and test it by making requests such as GET and POST to the provided hyperlinks.

Main Advantages of REST Framework

  • Source code simplicity, flexibility, quality, and test coverage
  • A serialization engine that works with both ORM and non-ORM data sources.
  • Emitters, parsers, validators, and authenticators are pluggable and easily customizable.
  • Generic classes handle CRUD operations.
  • The views for Resources are clean and straightforward, leveraging Django’s new class-based views.
  • ModelResources support with out-of-the-box default implementations and input validation (optional support for forms as input validation).
  • Handling HTTP responses, as well as content type negotiation via HTTP Accept headers.
  • Pagination makes it easier to return paginated material in a format presented to arbitrary media types.
  • Metadata and querysets are published together.
  • Throttling management and permission classes (API may feature a RESTrictive throttle for unauthenticated requests, a less RESTrictive throttle for authenticated requests, etc.)