The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K…

Follow publication

Django Rest Framework — CRUD With DRF

--

In my previous blog, I have explained what is a REST API and how to create a simple REST API with Django Rest Framework.

In this blog, I am explaining how to create a CRUD functionality with Django REST Framework. Let’s get started.

Uploading this for Cover Image. Ignore this image.😅😅😅
  1. Creating a new Django Project and Initial setup for DRF

Initially let’s create a simple Django Application. I am creating a new Django project named drf. After creating, I am just migrating and running the server.

$ django-admin startproject drf
$ cd drf
$ python3 manage.py migrate
$ python3 manage.py runserver

Now let’s install the Django Rest Framework.

$ pip3 install djangorestframework markdown django-filter

The command installs Django Rest Framework for your project. Now I am just adding the rest framework app to our installed app. Don’t forget to do this part since it might bring you to error while running.

drf/settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # make Sure to add this line
]

Now we have successfully initialized our Django app. Now let's start creating our model.

2. Creating a new Django app and Model.

In this section, I am creating a new Django app named employee to store all the employee details.

$ python3 manage.py startapp employee

As usual, this command will create a new app in our project. After creating the app register or add it to the Installed Apps section.

drf/settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'student',
'employee' # Make Sure you add this line
]

Now let’s create our model. I am creating a model with the following attributes.

employee/models.py

from django.db import models# Create your models here.
class Employee(models.Model):
emplyee_regNo = models.TextField(unique=True)
emplyee_name = models.TextField()
employee_email = models.TextField()
employee_mobile = models.TextField(null=True)
created_at = models.DateTimeField(auto_now=True)

After creating just execute these two commands where the first command creates a migration file in our app and the next one makes the changes in the database.

$ python3 manage.py makemigrations
$ python3 manage.py migrate

So we have successfully set our initial setup and model. Now let’s start creating our APIs.

3. Create API View

To perform CRUD API, DRF provides us some generic classes such as createAPIView, updateAPIView, listAPIView, destroyAPIView and so on.

In DRF, the Create API view helps us to add or insert values to the database.

CreateAPIView in DRF is a create-only API end-point. It supports only post request.

To perform create operation, I am creating two files in my app(serializer.py and api.py ). If you have any doubt about why we are creating this, have a look at my previous blog.

employee/serializer.py

from rest_framework import  serializers
from .models import Employee
class EmployeeSerializer(serializers.ModelSerializer):
class Meta:
model = Employee
fields = '__all__'

To use Create API view, we should use a generic class named CreateAPIView.

employee/api.py

from rest_framework import generics
from rest_framework.response import Response
from .serializer import EmployeeSerializer
from .models import Employee
class EmployeeCreateApi(generics.CreateAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer

Now I am just creating a file named urls.py in my employee app and mapping the API endpoint to a URL.

employee/urls.py

from django.urls import path
from .api import EmployeeCreateApi
urlpatterns = [
path('api/create',EmployeeCreateApi.as_view()),
]

Since I haven’t included the employee/urls.py in the project level urls.py, I am doing it now.

drf/urls.py

from django.conf.urls import url
from django.urls import path, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
path('student/', include('student.urls')),
path('employee/', include('employee.urls')),
]

Now everything must be fine to add an Employee detail via API when you visit the URL http://localhost:8000/employee/api/create.

Employe Create API

4. List API view

Now let’s do the same for retrieving all the employee details from the database. To perform this, I am using List API View. This API view supports only get request.

So now let’s start creating our view. Since we have created our serializer class in the previous section, we need not create it again. We can use the same serializer here also.

employee/api.py

class EmployeeApi(generics.ListAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer

Once done, just map this API endpoint to our URL.

employee/urls.py

from django.urls import path
from .api import EmployeeCreateApi, EmployeeApi
urlpatterns = [
path('api',EmployeeApi.as_view()),
path('api/create',EmployeeCreateApi.as_view()),
]

Now you can see all the employee details once the URL http://localhost:8000/employee/api has been snapped.

Employee List API

5. Update API View

Updating can be performed simply by replacing, the ListAPIView with RetriveUpdateAPIView. This API view supports both get, put, and patch requests.

employee/api.py

class EmployeeUpdateApi(generics.RetrieveUpdateAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer

The tricky thing here is that you should include the employee id in the URL. To achieve that, you can use <int: pk>.

employee/urls.py

from django.urls import path
from .api import EmployeeCreateApi, EmployeeApi, EmployeeUpdateApi
urlpatterns = [
path('api',EmployeeApi.as_view()),
path('api/create',EmployeeCreateApi.as_view()),
path('api/<int:pk>',EmployeeUpdateApi.as_view()),
]

If you make a put or patch request to http://localhost:8000/employee/api/<your _employee_id>, you can update employee details in the database.

Employee Update Api View

6. Delete API view:

At last, the Delete View. To perform this, DRF provides us DestroyAPIView. This API view provides us only delete request.

employee/api.py

class EmployeeDeleteApi(generics.DestroyAPIView):
queryset = Employee.objects.all()
serializer_class = EmployeeSerializer

After creating your view, just do the same as what you did for the update API view. Create another URL with id included in the route.

employee/urls.py

from django.urls import path
from .api import EmployeeCreateApi, EmployeeApi, EmployeeUpdateApi, EmployeeDeleteApi
urlpatterns = [
path('api',EmployeeApi.as_view()),
path('api/create',EmployeeCreateApi.as_view()),
path('api/<int:pk>',EmployeeUpdateApi.as_view()),
path('api/<int:pk>/delete',EmployeeDeleteApi.as_view()),
]

Once you call the delete API URL (http://localhost:8000/employee/api/<your _employee_id>/delete), it will automatically delete the particular employee details.

Employee Delete API View

If you have a problem with creating and installing DRF, do visit my previous blog.

In my next blog, I will be explaining how to protect every API route and home to perform JWT auth with Django rest Framework. Stay Connected.

Feel free to contact me for any queries.

Email: sjlouji10@gmail.com

Linkedin: https://www.linkedin.com/in/sjlouji/

Complete Code can be found on my Github: https://github.com/sjlouji/Django---DRF-basic-Rest-API-.git

Happy coding…

--

--

The Startup
The Startup

Published in The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +772K followers.

Sjlouji
Sjlouji

Written by Sjlouji

Software Engineer at @Pando. Developer | Writer. From ABC to the world of code.

Responses (3)

Write a response