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.