Quick Guide to making Rest API using Django

Quick Guide to making Rest API using Django

Make RESTFul API before your food gets delivered...

Hello there, in this article we will learn how to quickly make a CRUD RESTFul API in the Django rest framework. Few pre-requisite we assume that the reader knows python, very basics of Django, and have an understanding of MVC or MVT architecture

So first let's create a virtual environment, it is an optional step but is good practice to have project dependencies portable. Refer to Virtual Env guide to making one for this project.

Now let's install Django after that DjangoRestFramework and create our project.

pip install django
pip install djangorestframework

Creating Project in django

django-admin startproject 'project_name'
#django-admin startproject Marvel

go to the project directory

Create an app with the below command, one thing here is one project can have many apps and the ones we are using should be added in the settings.py file of our project inside INSTALLED_APPS[]. So we need to add our 'app_name' and 'rest_framework' to the list.

python manage.py startapp 'app_name'
#python manage.py startapp Spiderverse

We have our project ready now and the app inside as well. Open it in any IDE and go to the models.py file of your app. Quick overview it has the structure of our model(s) which is our database representation of the entity.

Here is guide to make model quickly and refer this for more insight. Below is a sample model for your reference

Marvel/Spiderverse/models.py

from django.db import models


class Spiderverse(models.Model):
    name= models.CharField(max_length = 50)
    description= models.TextField()

Now we need a Serializer class for our model, we can create it from scratch for each field of the model and have separate update() and create() methods overridden or we could just use model serializers to make things easy and quick.

Why do we need Serializers in the first place? in simple terms, serializer return data into python native datatypes from complex datatypes like Queryset, and native data can be easily converted to JSON or XML, etc which makes data representation easy.

Marvel/Spiderverse/serializers.py

from rest_framework import serializers
from .models import Spiderverse


class SpiderSerializers(serializers.ModelSerializer):
    class Meta:
        model = Spiderverse
        fields = "__all__"

Now we will move towards creating views for our mini project, views will have most of our logic of CRUD. We will use here class-based views that reuse already created code functionality from generics classes and mixins that have commonly used logic.

For example, our code logic for get() and post() method which we can overwrite using mixins that will be common for every model is already implemented in generics classes we just have inherited that code. Below is the implementation of get() post() method if we use mixin for creating and listing all the elements of the class.

class SpiderverseList(mixins.ListModelMixin, mixins.CreateModelMixin, generics.GenericAPIView):
    queryset = Spiderverse.objects.all() 
    serializer_class = SpiderSerializer 

    def get(self, request, *args, **kwargs): 
        return self.list(request, *args, **kwargs) 

    def post(self, request, *args, **kwargs): 
        return self.create(request, *args, **kwargs)

Now if we use generics.ListCreateAPIView, instead of the mixins we used above, generics have already implemented these methods for us, we will just inherit the class and assign modelserializer and queryset.

Marvel/Spiderverse/views.py

from .models import Spiderverse 
from .serializers import SpiderSerializer 
from rest_framework import generics 


class SpiderverseList(generics.ListCreateAPIView):
    queryset = Spiderverse.objects.all() 
    serializer_class = SpiderSerializers 

class SpiderverseDetail(generics.RetrieveUpdateDestroyAPIView): 
    queryset = Spiderverse.objects.all()
    serializer_class = SpiderSerializers

for Retrieve, Update, and Delete part of our implementation we used generics.RetrieveUpdateDestroyAPIView class. Now the final thing is to set up URLs for each view in urls file. Add the application to the projects urls.py file.

Marvel/urls.py

from django.urls import path, include 


urlpatterns = [path('', include('Spiderverse.urls'))]

and below code is for our app.

Marvel/Spiderverse/urls.py

from django.urls import path 
from .views import SpiderverseList, SpiderverseDetail 


urlpatterns = [ path('spider/', SpiderverseList.as_view()), 
path('spider/<int:pk>/', SpiderverseDetail.as_view()) ]

so this is it below our mini RESTFul API is ready and we can perform operations using given URLs and parameters. I have used postman for this example you can use any frontend you have, django forms or curl, etc options.

Last but not least, Do not forget to make migrations to make a database for our model.

python manage.py makemigrations
python manage.py migrate

Refer django and django restframwrok for a detailed guide.