Django Rest API using Django REST Framework- Introduction

Hi guys, today we start to learn Django Rest API using Django REST Framework. This is the introductory part of our tutorial. We learn to build a blog API for a blog site.

Start a project

Let’s create a project codekit and navigate to it and create an app named codekitapp using the following command.

django-admin startproject codekit
cd codekit
python manage.py startapp codekitapp

Open the project in an IDE or text editor and add the app to the project.

Now we will create two models. First one is category and follow below code:

class Category(models.Model):
    name = models.CharField(max_length=50)
    details = models.TextField()

    def __str__(self):
        return self.name.title()

    class Meta:
        verbose_name = 'Category'
        verbose_name_plural = 'Categories'

Another model named article that has a foreign key to category and User model of Django built-in DB:

class Article(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    image = models.ImageField(
        upload_to='upload/' + str(timezone.now().year) + "-" + str(timezone.now().month) + "-" + str(timezone.now().day))
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    author=models.ForeignKey(User, on_delete=models.CASCADE)
    def __str__(self):
        return self.title.title()

Now migrate the DB and add to admin to show in Django’s built-in administration

python manage.py migrate
python manage.py makemigration codekitapp
python manage.py migrate

Setup the Django REST API

Now install Django-rest framework, markdown, and filter using the following commands

pip install djangorestframework
pip install markdown
pip install django-filter

Add rest framework in setting.py:

INSTALLED_APPS = [
    ...............
    'rest_framework',
]

Add URL for login and registration

from django.urls import path, include
urlpatterns = [
    ............
    path('auth/', include('rest_framework.urls'))
]

Create a serializer class

Now create a serializer class and add the following code

from rest_framework import serializers
from codekitapp.models import Category
class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ['id', 'name', 'details']

CRUD Operation on Category

Read

Import the serializer class, ListAPIView and category Model in views.py. Then create a class that will inherit ListAPIView like the following code:

from rest_framework.generics import ListAPIView
from codekitapp.models import Category
from codekitapp.serializer import CategorySerializer
class CategoryListAPIView(ListAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

Create urls.py in codekitapp and add a path which will navigate to category like below:

from django.urls import path
from codekitapp.views import CategoryListAPIView
urlpatterns = [
    path('category', CategoryListAPIView.as_view())
]

Add this urls.py to the root app’s URL:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    ............
    path('auth/', include('rest_framework.urls')),
    path('api/', include('codekitapp.urls'))
]

Now run the project using python manage.py runserver and hit http://127.0.0.1:8000/api/category. You will see the category in the REST format.

Create

Now let’s create a CreateAPIView to add category data in views.py:

from rest_framework.generics import ListAPIView, CreateAPIView
class CategoryCreateAPIView(CreateAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()

Now add another URL path in codekitapp for CategoryCreateAPIView class like below:

from codekitapp.views import CategoryListAPIView, CategoryCreateAPIView

urlpatterns = [
    path('category', CategoryListAPIView.as_view()),
    path('category/create', CategoryCreateAPIView.as_view())
]

visit http://127.0.0.1:8000/api/category/create and you will see a post view like the below image.

Create API View

Retrieve

Now we create a RetrieveAPIView to view a category using its id. Let’s create a new class named CategoryDetailsAPIView like below:

class CategoryDetailsAPIView(RetrieveAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()
    lookup_field = 'id'
    lookup_url_kwarg = 'id'

Here we add two more lines. First-line indicates the database attribute field which we will match to show a single category and the second field indicates the query parameter of our URL. So let’s add the path in urls.py

from codekitapp.views import CategoryListAPIView, CategoryCreateAPIView, CategoryDetailsAPIView

urlpatterns = [
    path('category', CategoryListAPIView.as_view()),
    path('category/create', CategoryCreateAPIView.as_view()),
    path('category/<id>', CategoryDetailsAPIView.as_view())
]

Now if we visit http://127.0.0.1:8000/api/category/1, it will retrieve the category which id is 1 and show us as a single category JSON object like below

Retrieve API view

Update

To create a UpdateAPIView, add a new class in views.py like below:

from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView, UpdateAPIView
class CategoryUpdateAPIView(UpdateAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()
    lookup_field = 'id'
    lookup_url_kwarg = 'id'

It will also look up the field to update data. Now add a path in urls.py:

from django.urls import path
from codekitapp.views import CategoryListAPIView, CategoryCreateAPIView, CategoryDetailsAPIView, CategoryUpdateAPIView

urlpatterns = [
    ..............
    path('category/update/<id>', CategoryUpdateAPIView.as_view())
]

Now you can update the category hitting on http://127.0.0.1:8000/api/category/update/1

Delete

Let’s create the last portion of our API CRUD operation. Add new class in views.py and follow below coding snippet:

from rest_framework.generics import DestroyAPIView

class CategoryDeleteAPIView(DestroyAPIView):
    serializer_class = CategorySerializer
    queryset = Category.objects.all()
    lookup_field = 'id'
    lookup_url_kwarg = 'id'

Add URL like before we use.

from codekitapp.views import CategoryDeleteAPIView
urlpatterns = [
    ...............
    path('category/delete/<id>', CategoryDeleteAPIView.as_view())
]

Visit http://127.0.0.1:8000/api/category/delete/1 and you will ask you to delete like below.

That’s all about today’s tutorial. We will do things for the article model in a more efficient way.

You can collect full source code from here

56 Views

About Author

Nasir

Welcome to CodeKit.xyz. I am working in an automation company as a software engineer. From the deep thirst of learning, I have developed this platform.