Create REST API using Django Rest Framework

  512 views   7 months ago Python

There are multiple ways to indite an API in Django, but I don't optate you confound them. I will show you the two best ways to implement APIs, which will cover virtually all the scenarios.

Both ways are homogeneous to each other. They are:

  • APIView
  • ModelViewSet

APIView is more generic, while ModelViewSet is categorical to a Model's CRUD operations (i.e. ModelViewSet is utilized to perform List, Engender, Read, Update, Expunge (CRUD ) operations only.) Whereas with APIView, you can implement not only CRUD operations but additionally other Non-CRUD functionalities like authenticate, logout, engender invoice, download invoice, change fields of multiple models, etc.

You must be cerebrating, "with APIView we can implement so much, why to learn ModelViewSet?" Well, you will decipher the reason very anon after implementing them both.

Let's commence with APIView first.

Prerequisite

Create a Django project and application using the following steps.

# Install django in your system from command prompt
pip install django

# Create Project
django-admin startproject DemoProject

# Create Application inside the Project
cd DemoProject
django-admin startapp DemoApplication

# Add DemoApplication in settings.py > INSTALL_APPS list
INSTALLED_APPS = [
     ...
    'DemoApplication',
]

Install Django Rest Framework

# Install django rest framework from command prompt
install djangorestframework
# Add rest_framework application in settings.py > INSTALLED_APPS list
INSTALLED_APPS = [
    ...
    'rest_framework',
]

Now, we are ready with the Django Rest Framework setup. Let's create our first API using APIView.

APIView

With APIView, we can implement Get, Post, Delete, Patch, Put methods. Let's create a Book data model and implement CRUD functionality on it.

Edit the file -  DemoProject > DemoApplication > models.py and create a model. (Django will create a new SQL table in Database.)

class Book(models.Model):
    id=models.IntegerField(primary_key=True)
    title=models.CharField(max_length=200)
    author=models.CharField(max_length=200)

Edit the file - DemoProject > DemoApplication > views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from .models import *
from .serializers import *
from rest_framework import viewsets

# Create your views here.
class BookApiView(APIView):
    def get(self,request):
        allBooks=Book.objects.all().values()
        return Response({"Message":"List of Books", "Book List":allBooks})

    def post(self,request):
            Book.objects.create(id=request.data["id"],
                            title= request.data["title"],
                            author= request.data["author"]
                            )
        book=Book.objects.all().filter(id=request.data["id"]).values()
        return Response({"Message":"New Book Added!", "Book":book})

Edit the file - DemoProject > urls.py

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from ApiApplication import views

urlpatterns = [
    path('admin/', admin.site.urls),
    url("book/",views.BookApiView.as_view()), #new
]

Now, Migrate and run the project.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Open 127.0.0.1/book/ from your browser.

Voila! Your first API has created. 

Now Imagine, We have 10 data models (tables in database) and we have to create 10 such APIS and also implement CRUD functionality for the same. Isn't that a redundant task?

 To avoid repetitive code, Django has ModelViewSet where you can save 1000 of such lines.

ModelViewSet

Edit the file -  DemoProject > DemoApplication > models.py and create a new data model.

class Student(models.Model):
    id=models.IntegerField(primary_key=True)
    first_name=models.CharField(max_length=20)
    last_name=models.CharField(max_length=20,null=True,blank=True)
    dob=models.DateField(null=True,blank=True)

Create a new file  -  DemoProject > DemoApplication > serializers.py

from rest_framework import serializers
from .models import *

class StudentSerializer(serializers.ModelSerializer):
    class Meta:
        model=Student
        fields = "__all__"

Edit the file -  DemoProject > DemoApplication > views.py

class StudentViewSet(viewsets.ModelViewSet):
    queryset = Student.objects.all()
    serializer_class=StudentSerializer

Edit the file - DemoProject > urls.py

from django.conf.urls import url
from ApiApplication import views
from rest_framework import routers
from django.urls import include

router = routers.DefaultRouter()
router.register('student',views.StudentViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',include(router.urls))
]

Now run the server and open 127.0.0.1/student/ from your browser.

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]