Learning Django Rest Framework : Part 1 - Buidling a simple CRUD API

Ajay TekamAjay Tekam
3 min read

Setup

// setup env
virtualenv -p python3 venv .
. venv\Scripts\Activate
pip3 install django djangorestframework djangorestframework-simplejwt

// setup projects and apps 
django-admin startproject schoolmanagement .
django-admin startapp api
django-admin startapp students

Project Settings

Update Settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'students',                    # add the apps into settings.py
    'api',                         # 
]
Update urls.py
from django.contrib import admin
from django.urls import path, include   # add include   

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/v1/', include('api.urls')), # add  path for 'api' 
]

Update students app

We are using students app for a model only, no api urls mapping.

Creating models models.py
from django.db import models

# Create your models here.
class Student(models.Model):
    uuid = models.CharField(max_length=10)
    name = models.CharField(max_length=50)
    age = models.IntegerField()
    subjects = models.CharField(max_length=50)
    degree = models.CharField(max_length=50)

    # shows this data in admin dashboard panel 
    def __str__(self):     
        return self.name
Update admin.py

Will import model to admin dashboard.

from django.contrib import admin
from .models import Student            # import Student model from models.py

# Register your models here.
admin.site.register(Student)

Not updating views.py in students app, since all the operations will be performed in api app.

Updating API app

Create serializers.py

convert complex data (like Django model instances) into native Python datatypes, which can then be easily converted to JSON, XML, or other formats. They also handle validation and can be used to create or update model instances from incoming data.

from rest_framework import serializers
from students.models import Student

class studentSerializers(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'
update views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from students.models import Student
from .serializers import serializers, studentSerializers
from rest_framework import status
from django.shortcuts import get_object_or_404

@api_view(['GET'])          # allows http methods
def getStudents(request):
    students = Student.objects.all()
    serializer = studentSerializers(students, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)


@api_view(['POST'])
def addStudents(request):
    serializer = studentSerializers(data=request.data) 
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def removeStudents(request, id):
    student = get_object_or_404(Student, id=id)
    student.delete()
    return Response({"message" : f"ID '{id}' deleted."}, status=status.HTTP_200_OK)


@api_view(['POST'])
def updateStudents(request, id):
    student = get_object_or_404(Student, id=id)
    serializer = studentSerializers(student, data=request.data) 
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  • Response : Response class is used to return data from API views in a consistent, flexible, and easy-to-use way. It’s similar to Django’s HttpResponse, but it's specially designed for REST APIs.

  • api_view : - It's a decorator provided by DRF. It wraps Django function-based views to add features like Request parsing (request.data), Content negotiation (JSON, etc.).

  • get_object_or_404 : This function tries to retrieve an object from the database, and if it doesn't exist, it automatically raises a 404 error. It performs a query on the given model with the provided lookup parameters. If the object exists, it returns it. If not, it raises a Http404 exception and returns a 404 Not Found response.

Update views.py
from django.urls import path
from . import views

urlpatterns = [
    path('getstudents/', views.getStudents),
    path('addstudents/', views.addStudents),
    path('removestudents/<int:id>', views.removeStudents),
    path('updatestudents/<int:id>', views.updateStudents),
]

Creating SuperUser and migrating models

// make migrations 
python manage.py makemigrations 

// migrate to sqlite db
python manage.py migrate

// create admin user
python manage.py createsuperuser

run the app

python manage.py runserver
0
Subscribe to my newsletter

Read articles from Ajay Tekam directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ajay Tekam
Ajay Tekam

I am working as a Cloud Engineer with experience in DevOps, automation, CICD, build pipelines, jenkins pipelines, version control, shell scripting, python automation, golang automation, cloud services (AWS, OCI, Azure), containers and microservices, terraform, ansible.