Django Rest Framework Beginner

Akshay TekamAkshay Tekam
4 min read

Setup:

Environment setup:

For environment or env we have to run some command:

virtualenv -p python venv
or
virtualenv -p python3 venv

Django Rest Framework Setup:

For installing Django Rest Framework installation:

python install django djangorestframework

Project and App Creation:

// For project 
django-admin startproject rest_example_main .
// the "." is create the project folder on root 

//For App creation
django-admin startapp api
        // we are creating api app with help of this we access other app through this
// create student app
django-admin startapp student

Project Setting:

Now we have to change some files in the “rest_example_main” project

  1. Update settings.py file the “INSTALLED_APPS”
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',   // this is a Rest Framework app           
    'api',              // this is a api app 
    'students',                            
]
  1. Update urls.py file add the api app url in this

     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 Student app

in this we have to add model for student. Now in the student app there is no ‘models.py’ we have to create this file in that folder.

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 the admin.py file this 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)

We don’t do any things in the views.py file because the all operation will be done in api app.

Update the API app

In this app we need to create serializers.py

In Django REST Framework (DRF), serializers are a fundamental component used to convert complex data types, such as Django model instances or querysets, into native Python data types (like dictionaries) that can then be easily rendered into JSON, XML, or other content types for APIs. They also handle the reverse process, known as deserialization, which involves converting incoming data (e.g., from a JSON request body) back into complex Python objects, often with built-in validation.

from rest_framework import serializers
from students.models import Student

class studentSerializers(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = '__all__'

Now we have to write a views.py file for CRUD operation

add this header on this page

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)

This all are method for get data, post data, Delete and update data.
we call this function from api.urls file.

Now Update the urls.py file with this code:

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),
]

Migration, Database setup and Create superuser

// 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

Add Student

You can add student once server is start
go to this url: http://127.0.0.1:8000/api/v1addstudents/
please check the your server address. Then paste this JSON

    {
        "uuid": "1",
        "name": "Akshay Tekam",
        "age": 29,
        "subjects": "MCA",
        "degree": "MCA"
    }

add at least 2 or 3 student then get all the data from http://127.0.0.1:8000/api/v1getstudents/ url

For Delete and Update

For delete you can use

// for Delete
http://127.0.0.1:8000/api/v1removestudents/<id of student>
0
Subscribe to my newsletter

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

Written by

Akshay Tekam
Akshay Tekam