How to Create a REST API in Django
Join the DZone community and get the full member experience.
Join For FreeThere are multiple ways to write an API in Django, but I don't want you confuse them. I will show you the two best ways to implement APIs, which will cover almost all the scenarios.
Both ways are similar to each other. They are:
- APIView
- ModelViewSet
APIView is more generic, while ModelViewSet is specific to a Model's CRUD operations (i.e. ModelViewSet is used to perform List, Create, Read, Update, Delete (CRUD ) operations only.) Whereas with APIView, you can implement not only CRUD operations but also other Non-CRUD functionalities like login, logout, generate invoice, download invoice, change fields of multiple models, etc.
You must be thinking, "with APIView we can implement so much, why to learn ModelViewSet?" Well, you will figure out the reason very soon after implementing them both.
Let's start with APIView first.
Prerequisite
Create a Django project and application using the following steps.
xxxxxxxxxx
# 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
xxxxxxxxxx
# 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.)
xxxxxxxxxx
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
xxxxxxxxxx
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
xxxxxxxxxx
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.
xxxxxxxxxx
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.
xxxxxxxxxx
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
xxxxxxxxxx
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
xxxxxxxxxx
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.
Compare the view class of APIView and ModelViewSet. In ModelViewSet, we saved lots of lines of code. Also, Django itself is implementing the CRUD functionality — fewer chances for us to make mistakes.
Opinions expressed by DZone contributors are their own.
Trending
-
MLOps: Definition, Importance, and Implementation
-
Microservices Decoded: Unraveling the Benefits, Challenges, and Best Practices for APIs
-
Managing Data Residency, the Demo
-
Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
Comments