Hi there,
Thanks for reading my article. This is my first article in the medium. Here I am going to describe each and everything about building REST API using the Django REST Framework. It will be a full CRUD operation using only one view class and one serializer class. Let’s do it together. First of all, we need to install the Django rest framework on our computer. Open the terminal/cmd, type the following command, and then hit enter
pip install djangorestframework
Now create a project named djangoCore
and an app named myApp
using the following command.
django-admin startproject djangoCore
cd djangoCore
python manage.py startapp myApp
Add myApp and rest-framework in djangoCore/settings.py
like following coding snippets.
INSTALLED_APPS = [
..................
'rest_framework'
'myApp'
..................
]
Create a model in myApp/models.py
, we are assuming a model like below.
class StudentRecord(models.Model):
name=models.CharField(max_length=200)
student_id=models.CharField(max_length=100)
department=models.CharField(max_length=100)
completed_credit=models.IntegerField()
blood_group=models.CharField(max_length=10)
phone_number=models.CharField(max_length=20)
Now migrate the model using the following command.
python manage.py makemigrations myApp
python manage.py migrate
Our project is ready to create API endpoints. Create a file named serializers.py
in the myApp directory and add the following coding snippets to serialize the data to reproduce the JSON object/array.
from rest_framework.serializers import ModelSerializer
from myApp.models import StudentRecord
class StudentSerializers(ModelSerializer):
class Meta:
model = StudentRecord
fields = '__all__'
We have only the last two-step to get our result. Go to the myApp/views.py
and create a class-based view which will inherit ModelViewSet. Suppose our view class is like below.
from rest_framework.viewsets import ModelViewSet
from myApp.models import StudentRecord
from myApp.serializers import StudentSerializers
class StudentView(ModelViewSet):
serializer_class = StudentSerializers
queryset = StudentRecord.objects.all()
Now create myApp/urls.py
and create an object of DefaultRouter(). Then register the URL for the created view. So codebase of our myApp/urls.py
will be
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from myApp.views import StudentView
router = DefaultRouter()
router.register('student', StudentView, basename='student')
urlpatterns = [
path('', include(router.urls))
]
DefaultRouter() includes routes for a set of list, create, update, retrieve, destroy actions. So we don’t need to implement every API endpoints in a separate view function/class.
We can also impose permission and authentication in all endpoints at the same time or in separate endpoints. But in this article, we don’t cover them up. Next, we will explore Mixins for separate actions of APIs. Thanks for reading the article.