An Application Programming Interface or API is a way for computers and servers to talk to each other on the web. Most of the APIs in the world is Restful, which means they follow a set of rules or constraints known as Representational State Transfer. They are typically a way to access a database. The API backend queries the database and formats the response.  A Restful API organizes data entities or resources into a bunch of unique URIs or Uniform Resource Identifiers that differentiate between different types of data resources. When a RESTful API request is made, the server will send a representation of the status of the requested resource and you will receive a static response in JSON format of the resource requested. REST APIs are so common in software development that it’s essential for developers to understand how they work. In this tutorial, we’ll create API in Django Rest Framework viewset.

Why Choose Django Rest Framework

Django REST Framework, or DRF, is an open-source, mature, and well-supported Python library. It aims to create sophisticated web APIs. Django REST Framework has many out-of-the-box features. However, the core view class of DRF is simple and the framework is generally easy to use. DRF is a way to clearly segregate a model. It also provides a generalized wire representation and standardized Class-Based Views which can be customized for specific API endpoints. Serializer describes the mapping between them.

Django Rest Framework allows you to use your Django Server’s REST API with ease. It also makes it easier to re-use code and autogenerate a lot of endpoints, formats options, and versioning. It separates the user interface from data storage and directly communicates with the database.

Architecture

DRF Web API is rich and web-browsable. It supports many media types, authentication, and permission policies right out of the box. API display data or even powerful class-based views can be viewed using standard functions and show more complex functionality. Therefore it is best to create api using Django rest framework viewset.

Serializers

Django REST Framework’s greatest benefit is its ease of serialization! This allows you to focus on the business logic and not the details of the implementation. Django ORM or Object Relational Mapping takes care of all this for you. Which already does all the heavy lifting in querying the database. Your data will be displayed as instances of your Model class in your Python code. However, an API will need to translate it into JSON format in order to communicate with your clients. Therefore it is best to create api using Django rest framework viewset.

This translation is handled by the DRF serializer. The serializer converts the information submitted by users (e.g. creating a new instance) into something Django can use to insert into a Model instance. You can serialize your database models using Django REST Framework in just a few lines.

Routers

The router is the final layer in your API’s surface layer. The DRF routers combine all URLs required for a particular viewset into one line. This allows you to avoid having endless „list“, “detail“, and „edit” URLs.

Building a Quick Small Application in DRF

We’ll be going to make a simple API to allow administrators to view and modify the groups and users in the system.

Installation

You can clone the DRF project from github.

git clone https://github.com/encode/django-rest-framework

or you can install all the necessary components using pip 

pip install djangorestframework # For the latest version of DRF
pip install markdown            # Use markdown wysiwyg in flatpages and admin forms
pip install django-filter       # Filtering support

Project setup

Create a Django project named drf_project, then start a new app called quickstart:

# Setup a new project and an app
django-admin startproject drf_project
cd drf_project
django-admin startapp quickstart
cd ..

Your projects’ layout should now look something like this:

pwd
<some path>/drf_project
find .
.
./manage.py
./drf_project
./drf_project/__init__.py
./drf_project/quickstart
./drf_project/quickstart/__init__.py
./drf_project/quickstart/admin.py
./drf_project/quickstart/apps.py
./drf_project/quickstart/migrations
./drf_project/quickstart/migrations/__init__.py
./drf_project/quickstart/models.py
./drf_project/quickstart/tests.py
./drf_project/quickstart/views.py
./drf_project/settings.py
./drf_project/urls.py
./drf_project/wsgi.py

After the app is created add register the app by adding the path to the app config. This can be located at drf_project/settings.py. Add this to the file:

INSTALLED_APPS = [
    ...
    'rest_framework',
]

You should also always sync your database at this point:

python3 manage.py makemigrations
python3 manage.py migrate

Setting Up DRF Serializers

Once that is done, tell DRF how you want to serialize your models. We’ll first define serializers. Create a module named drf_project/quickstart/serializers.py . It will be used for our data representations.

# serializers.py
from django.contrib.auth.models import User, Group
from rest_framework import serializers

class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']

Setting Up Routers and URLs

After the serializers are created we’d better write some views then, it is for the API and connects it to the Django URLs. Open drf_project/quickstart/views.py and add the 2 viewsets for each of the models we have created.

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from rest_framework import permissions
from tutorial.quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API’s endpoint that allows users to be modified.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer
    permission_classes = [permissions.IsAuthenticated]


class GroupViewSet(viewsets.ModelViewSet):
    """
    API’s endpoint that allows groups to be modified.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
    permission_classes = [permissions.IsAuthenticated]

Once the viewsets have been defined, we can use DRF’s router functionality to route an API endpoint to the desired viewset. Go on to drf_project/urls.py and add the following to your code.

from django.urls import include, path
from rest_framework import routers
from tutorial.quickstart import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

# Wire our API using automatic URL routing.
# Moreover, we can include login URLs for browsable APIs.
urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

Testing out our API

Now that everything is done, we should run our final migration by:

python3 manage.py migrate

Then we can run start our server:

python3 manage.py runserver

We can now access our API, directly through the browser, by going to the URL http://127.0.0.1:8000/users/

Also Read: Getting started with Machine Learning in Python

Final Words

With only that simple code, you can add an API layer to your already existing Django project. The power of an API lets you build amazing add-ons to existing apps. Or empowers your users with their own niche functionality that increases the value of what your app already offers. This tutorial will help you to create api using Django rest framework viewset.

We hope that this article has been an interesting read for you! REST APIs are a powerful tool that allows you to create a wide variety of services that can be accessed by a variety of clients. This blog post has been designed to not only teach you about the Django Rest Framework but also to provide you with some example code that you can use in your own projects. We hope that this article provided you with a solid introduction to DRF and that you will consider using it to build your own APIs.

Here are some useful tutorials that you can read: