[Django Rest Framework] Build Your First REST API with Python Django Rest Framework. (CRUD Operation)

Django REST framework is a powerful and flexible toolkit for building Web APIs.

Some reasons you might want to use REST framework:

The definition and reasons for using REST framework are retrieved from the home page of Django Rest Framework

In this tutorial, we will be building a REST API using the Django Rest Framework. The API performs the CRUD Operation of a Todo list Application developed in Django Framework.

Prerequisite

Before starting the tutorial following setup is necessary:

  1. Django Framework
  2. A Django Web App running on your localhost server.

If you are new to Django Development and haven’t build any web app with Django before that please go through following links:

  1. Django Framework Installation
  2. Create a New Django Application

It is also necessary to create a user such that we can add data in the database. For that, you will need to create superuser. Refer to the link below:

After all these, with assumption that you have a running djnago web app, let’s begin the development of REST API with Django Rest Framework

Install Django Rest Framework

First of all, we need to install the Django Rest Framework from pip. Type the following command in your terminal:

pip install djangorestframework

Once the Django Rest Framework has been installed add it in your settings file (settings.py)

INSTALLED_APPS = [
    ...
    'rest_framework',
]

Create an Application for your API

Creating an API is also creating another Django web application. Therefore from your terminal create an application:

python manage.py startapp api

Now that you have created an application named “api”, you can see a folder with different files such as admin.py, apps.py, models.py, tests.py and views.py. After the application is created you need to register that app in your settings as installed apps.

INSTALLED_APPS = [

‘api.apps.ApiConfig’,
‘rest_framework’,
]

Create a Model

First lets create a model for todo app. Add the following code in your models.py:

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    completed = models.BooleanField(default=False, blank=True, null=True)

    def __str__(self):
        return self.title

The todo list api adds tasks and the status of tasks.

Create a Serializer

Here we are dealing with the data stored in a database which needs to be retrieved via web requests with the help of API. Therefore the best way of fetching the data is in the form of JSON. So we need to parse the data from database in JSON format. The serielizer does the job. Create a file named (serializer.py)

from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = '__all__'

Configure URLs

We are configuring URLs in the following approach.

  1. Create URL for api web app
  2. Link that api url to Django Project’s main URL

In urls.py add the following URL path:

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

Now in the api folder which is your app, create a file urls.py and add the following paths:

from django.urls import path
from . import views

urlpatterns = [
    path('', views.apiOverview, name="api-overview"),
    path('task-list', views.taskList, name="task-list"),
    path('task-detail/<str:pk>/', views.taskDetail, name="task-detail"),
    path('task-create/', views.taskCreate, name="task-create"),

    path('task-update/<str:pk>/', views.taskUpdate, name="task-update"),
    path('task-delete/<str:pk>/', views.taskDelete, name="task-delete"),
]

Create your View

We have to build models and serializer. Now our task is to create a view where we perform CRUD operations. Since we have configured the URLs.

API Overview

In our view, we will create a first view that lists all the URLs that are going to be exposed. We shall be using a decorator api_view provided by the rest framework. We need to import the TaskSerializer we build earlier. The task serializer parses the request from the database and represents JSON strings

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import TaskSerializer

from .models import Task
# Create your views here.

@api_view(['GET'])
def apiOverview(request):
    api_urls = {
        'List': '/task-list/',
        'Detail View': '/task-detail/<str:pk>/',
        'Create': '/task-create/',
        'Update': '/task-update/<str:pk>/',
        'Delete': '/task-delete/<str:pk>/',
    }
    return Response(api_urls)

Run your server and browse the url: http://127.0.0.1:8000/api/

This lists all the requests we can make to the API. Next we will see the list of tasks added in the todo list application. Before that goto the admin site from your browser http://127.0.0.1:8000/admin/ and add a few tasks.

Remember the basics:

In order to add items in the database, you should first register your model Task in the admin.py file

from django.contrib import admin
from .models import Task
# Register your models here.

admin.site.register(Task)

Just in case you face this error related to django_session while loading the api Error: OperationalError at /api/ no such table: django_session. Check the following URL to fix this minor issue:

API TaskList

Now in our views we will create an another method to add to list all the items from the database.

@api_view(['GET'])
def taskList(request):
    tasks = Task.objects.all()
    serializer = TaskSerializer(tasks, many=True)
    return Response(serializer.data)

This API can be browsed from the browser via the following URL: http://127.0.0.1:8000/api/task-list

You will see the following responses:

This api request listed all the items in your todo list. Now in order to view the individual items lets create another method.

TaskDetail

This API method will list the details of items based upon the id.

@api_view(['GET'])
def taskDetail(request, pk):
    tasks = Task.objects.get(id=pk)
    serializer = TaskSerializer(tasks, many=False)
    return Response(serializer.data)
We can view the response from thie URL: http://127.0.0.1:8000/api/task-detail/1/
HTTP 200 OK
Allow: OPTIONS, GET
Content-Type: application/json
Vary: Accept

{
    "id": 1,
    "title": "Donot To Verify that Admin can create a School",
    "completed": true
}

Task Create

This method created tasks i.e. stored the items to database:

@api_view(['POST'])
def taskCreate(request):
    serializer = TaskSerializer(data=request.data)

    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

The task can be created from the url: http://127.0.0.1:8000/api/task-create/

Task Update and Delete

Now we will create two methods to update and delete the items in the todo list. The code below will provide the facility of updating and deleting items via URL.

@api_view(['POST'])
def taskUpdate(request, pk):
    task = Task.objects.get(id=pk)
    serializer = TaskSerializer(instance=task, data=request.data)

    if serializer.is_valid():
        serializer.save()
    return Response(serializer.data)

@api_view(['DELETE'])
def taskDelete(request, pk):
    task = Task.objects.get(id=pk)
    task.delete()
    return Response("Task Deleted Successfully")

URL to Update the task: http://127.0.0.1:8000/api/task-update/1/
URL to Delete task: http://127.0.0.1:8000/api/task-delete/5/