Create a CRUD API in Django in just 15 minutes

In this article we are going to create a CRUD (Create, Read, Update, Delete) API using Django framework in just 15 minutes. We assume you already know Basics of Django framework.

Installation

First install Django framework

pip install Django

Now start a new django project

django-admin startproject crud

Above crud is the name of your project

 

Now create a new app (named employee) inside project

python manage.py startapp employee

In this app , we are going to create two model classes 

 

Models

Employee

class department(models.Model):
    department_id = models.CharField(primary_key=True, default=uuid_str, max_length=100)
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

 

 

Department

class employee(models.Model):
    employee_id = models.CharField(primary_key=True, default=uuid_str, max_length=100)
    name = models.CharField(max_length=100)
    contract_employee = models.BooleanField(default=True)
    department = models.ForeignKey(department, on_delete=models.SET_NULL, null=True, blank=True)
    age = models.IntegerField()
    address = models.TextField()

    def __str__(self):
        return self.name

 

Once the model classes are ready, install the employee application in settings.py 

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'employee',
]

See the last row in above snippet where we have added employee application

Once application is installed. Run migrations to create relevant database tables

python manage.py makemigrations
python manage.py migrate

Django Rest Framework

Now to create JSON REST api, we will need one additional package, called Django Rest Framework

pip install djangorestframework

we are using version 3.10.2 of django rest framework

Install two new apps to your application in settings.py file

    'rest_framework',
    'rest_framework.authtoken'

So once you add above two apps to your project in settings.py file

INSTALLED_APPS will now look like this (see last 2 rows)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'employee',
    'rest_framework',
    'rest_framework.authtoken',
]

in above snippet

'rest_framework' is the framework for creating rest api

'rest_framework.authtoken' is required for creating db tables for storing authentication token.

again run migrations , that will create required table for storing authorization token

 

Serializers

To create rest api in django we need serializers classes.

To do this first create serializers.py file in your app directory (which is employee in our article)

from rest_framework import serializers
from employee.models import employee, department


class EmployeeSerializer(serializers.ModelSerializer):

    class Meta:
        model = employee
        fields = '__all__'


class DepartmentSerializer(serializers.ModelSerializer):

    class Meta:
        model = department
        fields = '__all__'

As you can see in above snippet , we have create two serializers for employee and department model classes

 

Now we can create views for our API

from django.shortcuts import render
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from .models import employee, department
from .serializers import EmployeeSerializer, DepartmentSerializer
from django.http import Http404


# Create Department
@api_view(['POST'])
def department_create(request):
    '''
    Create department object
    '''
    serializer = DepartmentSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET', 'POST', 'DELETE'])
def department_interact(request, department_id):
    '''
    Update/delete department object
    '''
    try:
        d = department.objects.get(department_id=department)
    except d.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializer = DepartmentSerializer(d)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = DepartmentSerializer(d, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        d.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)

As you can see we have created two views

1. department_create : this view can be used to create a department object and store it in your DB 

2. department_interact :  this view can be used to update (POST HTTP verb), delete (DELETE HTTP verb) and retrieve (GET HTTP verb) department object in db table 

We can also create a department list view

@api_view(['GET'])
def department_list(request):
    dlist = department.objects.all()
    serializer = DepartmentSerializer(dlist, many=True)
    return Response(serializer.data)

Next we are going to create similar views for employees model

@api_view(['GET', 'POST', 'DELETE'])
def employee_interact(request, employee_id):
    try:
        e = employee.objects.get(employee_id=employee_id)
    except e.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)
    if request.method == 'GET':
        serializer = EmployeeSerializer(e)
        return Response(serializer.data)
    elif request.method == 'POST':
        serializer = EmployeeSerializer(e, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    elif request.method == 'DELETE':
        e.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


@api_view(['POST'])
def employee_create(request):
    '''
    Create employee object
    '''
    serializer = EmployeeSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def employee_list(request):
    '''
    Get employee list
    '''
    elist = employee.objects.all()
    serializer = EmployeeSerializer(elist, many=True)
    return Response(serializer.data)

Next we can expose each view using urls.py

from django.contrib import admin
from django.urls import path
import employee.views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', employee.views.echo, name="echo"),
    path('api/department/add', employee.views.department_create, name="department_create"),
    path('api/department/list', employee.views.department_list, name="department_list"),
    path('api/department/interact/<uuid:department_id>', employee.views.department_interact, name="department_interact"),

    path('api/employee/add', employee.views.employee_create, name="employee_create"),
    path('api/employee/interact/<uuid:employee_id>', employee.views.employee_interact, name="employee_interact"),
    path('api/employee/list', employee.views.employee_list, name="employee_list"),
]

Now you can deploy this django rest api.
This was a basic example of creating simple CRUD api using django rest framework.

You can clone full project from this github repository

Github Repo