Django REST Framework is a library which works on top of Django. It can be called a Microframework. In django we return a HttpResponse object from views. But in DRF we return JSON object. DRF helps to create an  RESTful API endpoint. “Browsable API” was stated as the key factor in picking Django REST framework.

What is an API?

If you are totally new to development, you might have never heard about API. It’s totally okey. But did you ever think how data travel from one application to another?

API does that. It stands for Application Programming Interface. APIs transport data from one app to another. So, API is a messenger that takes request and returns the response or a software intermediary that allows two applications to talk to each other.

Think of a website that compares mobile phones of different brands. The site doesn’t have the information of each model of each brand in its database. Then how do they compare? Each time a user selects a mobile model, the backend of PhoneCompare site sends a request through the API to its manufacturer’s website to send information. If the request is valid the API comes with the response.

This is how it retrieves data and then compares them using it’s own mechanism.

What is JSON?

JSON stands for JavaScript Object Notation. It is a standard text-based format of representing, storing and transporting data. JSON is often used when data is sent from a server to a web page. JSON is lightweight. It’s almost like a Python Dictionary.

[
 {
    "name": "Jon Snow",
    "age": 29,
  },
  {
    "name": "Arya Stark",
    "age": 21,
  }
]

We have gathered enough knowledge on prerequisites to work with Django REST Framework.

How To Install and Setup Django REST Framework?

Let’s start with installing it in our system. Run this command in your terminal or powershell.

pip install djangorestframework

Or we can clone it from github repository

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

We have created a django project before. Now we will  Add 'rest_framework' to our INSTALLED_APPS in settings.py.

INSTALLED_APPS = [
    ...
    'rest_framework',
]

We are all set to start creating APIs. We have a django application ‘first_app’. There we have a ‘Person’ model. We will create an API to fetch all the objects of the Person model. First of all, we will have to create a serializers.py file inside of our app. What is a serializer? Read Here.

Inside serializers.py let’s add this code snippet.


from rest_framework import serializers
from .models import Person

class PersonSerializers(serializers.ModelSerializer):
    
    class Meta:
        model = Person
        fields = ['first_name','last_name','gender']

In simple words, we just told django that we want these (‘first_name’, ‘last_name’, ‘gender’) fields of our ‘Person’ class to be sent/fetched through our API.

Function Based API

We can create API using both python function & python class. Let’s see function based api first. It’s nothing but a function-based view. ‘@api_view’ decorator converts that function into an api. @api_view decorator wants a list of HTTP methods [GET, POST, PUT, PATCH, DELETE] as a required argument.


from rest_framework.response import Response
from rest_framework.decorators import api_view


@api_view(['GET'])
def person_api_view(request):
    
    persons = Person.objects.all()
    serializer = PersonSerializers(persons, many=True)
    return Response(serializer.data)

urls.py

path('api/persons/function', views.person_api_view),

Let’s run our server and hit that api endpoint. We should see some output like this.

We got all the objects but didn’t show in this picture. Now we will do the same thing using Class Based View.

Class Based API

For now, we are introducing APIView. APIView class is almost the same as using a regular View class. As usual, the incoming request is dispatched to an appropriate handler method such as  .post(). Additionally, a number of attributes can be set inside that class to control various aspects of the API policy.


from rest_framework.views import APIView from rest_framework import authentication, permissions from rest_framework.response import Response from .serializers import PersonSerializers class PersonAPIView(APIView): def get(self, request): """ Return a queryset of all users. """ persons = Person.objects.all() serializer = PersonSerializers(persons, many=True) return Response(serializer.data)

endpoint:

path('api/persons/', views.PersonAPIView.as_view()),

Output:

As we have told before we can add different attributes to control API policy. Let’s see an example of it.

Assume that we want to give permission to access our API to our admins only. We can set a ‘permission_classes’ attribute.

from rest_framework import permissions
from .serializers import PersonSerializers

class PersonAPIView(APIView):

    permission_classes = [permissions.IsAdminUser]

This will restrict unauthenticated and unauthorized users to access our API. Now we are logged in as admin, let’s get logged out and go to the URL. We will end up seeing a 403 Forbidden error.

But if we log in again as admin the endpoint will return response as before.

In this tutorial we have had an introduction to API, JSON & How actually REST framework works. We will discuss deep in our next tutorials.

+ posts

Author | Python-Django Developer

+ posts

Full-stack Developer (Python | Django | React | React-Native | Angular | Vue)