Build REST API using Django REST framework in 15 minutes :)

Pushpraj Gupta
5 min readJun 7, 2021

--

Magic powers shown in visual form !

What the hell is REST API ?

An API is an application programming interface. It is a set of rules that allow programs to talk to each other. The developer creates the API on the server and allows the client to talk to it.

REST determines how the API looks like. It stands for “Representational State Transfer”. It is a set of rules that developers follow when they create their API. One of these rules states that you should be able to get a piece of data (called a resource) when you link to a specific URL.

Each URL is called a request while the data sent back to you is called a response.

So lets understand this with an example :

Let’s say you’re trying to find videos about Ironman on Youtube. You open up Youtube, type “Ironman” into a search field, hit enter, and you see a list of videos about Ironman. A REST API works in a similar way. You search for something, and you get a list of results back from the service you’re requesting from.

There are a few key options for a REST API request:

  • GET — The most common option, returns some data from the API based on the endpoint you visit and any parameters you provide
  • POST — Creates a new record that gets appended to the database
  • PUT — Looks for a record at the given URI you provide. If it exists, update the existing record. If not, create a new record
  • DELETE — Deletes the record at the given URI
  • PATCH — Update individual fields of a record

Lets make an API now :

Project Setup

1. Create the Project Directory

mkdir demo
cd demo

2. Create the Virtual Environment

python3 -m venv env
source env/bin/activate #in Unix or MacOS
env\Scripts\activate.bat #in Windows

3. Install Django and Django REST framework

pip install django
pip install djangorestframework

4. Setup a new project with single app

django-admin startproject demo.  # Note the trailing '.' character
cd demo
django-admin startapp marvel
cd ..

5. Add rest_framework and marvel to the INSTALLED_APPS inside the settings.py file.

# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'marvel'
]

6. Now sync your database for the first time:

python manage.py migrate

7. Create superuser:

python manage.py createsuperuser

8. Test the Django server:

python manage.py runserver

And go to localhost:8000/admin and login

Django admin login page

Models

1. Create Model in marvel/models.py :

from django.db import models

# Create your models here.

class Avenger(models.Model):
name = models.CharField(max_length=100)
superpower = models.CharField(max_length=100)
def __str__(self):
return self.name

2. Register Avenger with the admin site in marvel/admin.py:

from django.contrib import admin
from .models import Avenger
admin.site.register(Avenger)

3.Make migrations :

$ python manage.py makemigrations
Migrations for ‘marvel’:
marvel\migrations\0001_initial.py
— Create model Avenger
$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, marvel, sessions
Running migrations:
Applying marvel.0001_initial... OK

4.Now login to admin and create some Avenger there:

$ python manage.py runserver

go to localhost:8000/admin

Serializers

First up we’re going to define some serializers. Let’s create a new file named marvel/serializers.py that we'll use for our data representations.

Serialization is the process of converting a Model to JSON. Using a serializer, we can specify what fields should be present in the JSON representation of the model.

The serializer will turn our Avengers into a JSON representation so the API user can parse them, even if they’re not using Python. In turn, when a user POSTs JSON data to our API, the serializer will convert that JSON to a Avenger model for us to save or validate.

from rest_framework.serializers import ModelSerializer
from rest_framework import serializers
from .models import *

class AvengerSerializer(ModelSerializer):

class Meta:
model = Avenger
fields = ["name","superpower"]

Views

Now, we are creating views to display and create the data!

Open marvel/views.py and get typing.

from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializers import AvengerSerializer
from .models import Avenger

# Create your views here.

class AvengerView(APIView):

def get(self, request):
list = []
query = Avenger.objects.all()
serializer = AvengerSerializer(query, many=True)
for data in serializer.data:
list.append(data)

return Response(status=status.HTTP_200_OK, data={'avengers': list})

def post(self, request):
attrs = {
"name" : request.data.get('name'),
"superpower" : request.data.get('superpower'),
}
Avenger.objects.create(**attrs)

return Response(status=status.HTTP_200_OK, data={'status': "success"})

Urls

  1. In Django, URLs get resolved at the project level first. So there’s a file in demo/ directory called urls.py .

Head over there. You’ll see the URL for the admin site is already in there. Now, we just need to add a URL for our API. For now, let’s just put our API at the index:

from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('marvel.urls')),
]

2. So, let’s go there next marvel/urls.py:

from django.urls import path
from django.conf.urls import url
from . import views

urlpatterns = [
url(r'^get_add_avenger/', views.AvengerView.as_view(), name='get_add_avenger'),
]

Now Check it out

Start up the Django server again:

$ python manage.py runserver

Now go to localhost:8000/get_add_avenger/

You can also use Postman for GET and POST request !

Thanks for your time :)

--

--

No responses yet