REST API using Django Rest Framework
In this article, we are going to see how we can create REST APIs in django using the django rest framework.
Create a new django project . Once the new django project is created, we are ready to start creating the APIs.
Create a new app in your project named "api" and add the "api" to your installed_apps list in the settings.py file. Now install the Django REST Framework click here and add "rest_framework" to your installed_apps list in the settings.py file as shown below.
INSTALLED_APPS = [
...
'django.contrib.staticfiles',
'api',
'rest_framework',
]
Now create a file, inside the api folder, with the name "urls.py" and include the "api/urls" file in the main/project's urls.py file as shown below:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls'))
]
Now any requests starting with "api/" will be directed to the api/urls.py file. We will write all the api paths in the api/urls file.
Let us create the table to store and retrieve the data. We will be creating a student table and store the following details. Open the api/models.py and add the model.
from django.db import models
# Create your models here.
class Student(models.Model):
name = models.CharField(max_length=100, null=False)
email = models.CharField(max_length=100, null=False)
phone = models.CharField(max_length=100, null=False)
def __str__(self):
return self.name
Now lets create a path as shown below:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="/"),
]
Now open the views.py file and create a function with the name "index". We will fetch the data from database and return the data as response. We will not be sending the JsonResponse. Instead we will serialize the data and we will be using the Response() provided by rest_framework to return the response.
To serialize the data, create a file in the app (/api/) directory and name it as serializers.py . Create a class with the model name followed by Serializer as shown below:
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
Now import the StudentSerializer in the views file and pass the database object in the serializer as shown below:
from rest_framework.response import Response
from rest_framework.decorators import api_view
from api.models import Student
# Create your views here.
from .serializers import StudentSerializer
@api_view(['GET'])
def index(request):
students = Student.objects.all()
serialstudents = StudentSerializer(students, many=True)
// Return a Response
return Response(serialstudents.data)
// Or If you want to specify custom status code along with the data, then follow the below structure
return Response({
'status':200,
'students':serialstudents.data
})
The @api_view() accepts a parameter of list of methods you want to allow for that function.
Similarly create the paths and the views for the CRUD as shown below:
Urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name="/"),
path('student-view/<str:pk>/', views.studentView, name="studentview"),
path('add-student/', views.studentAdd, name="studentadd"),
path('update-student/<str:pk>/', views.studentUpdate, name="studentupdate"),
path('delete-student/<str:pk>/', views.studentdelete, name="studentdelete")
]
Views.py
from rest_framework.response import Response
from rest_framework.decorators import api_view
from api.models import Student
# Create your views here.
from .serializers import StudentSerializer
@api_view(['GET'])
def index(request):
students = Student.objects.all()
serialstudents = StudentSerializer(students, many=True)
return Response({
'status':200,
'students':serialstudents.data
})
@api_view(['GET'])
def studentView(request, pk):
try :
student = Student.objects.get(id=pk)
serialstudent = StudentSerializer(student, many=False)
return Response({
'status':200,
'students':serialstudent.data,
})
except :
return Response({'status':400})
@api_view(['POST'])
def studentAdd(request):
try:
serialdata = StudentSerializer(data=request.data)
if serialdata.is_valid():
serialdata.save()
return Response({
'status':200,
'student':serialdata.data,
'message':'Student added successfully'
})
except:
return Response({'status':400})
@api_view(['POST'])
def studentUpdate(request, pk):
try :
student = Student.objects.get(id=pk)
serialstudent = StudentSerializer(instance=student, data=request.data)
if serialstudent.is_valid():
serialstudent.save()
return Response({
'status':200,
'student':serialstudent.data,
'message':'Updated successfully'
})
except :
return Response({'status':400})
@api_view(['DELETE'])
def studentdelete(request, pk):
try:
student = Student.objects.get(id=pk)
student.delete()
students = Student.objects.all()
serialstudents = StudentSerializer(students, many=True)
return Response({
'status':200,
'student':serialstudents.data,
'message':'Student Deleted successfully'
})
except:
return Response({'status':400})
Thanks for reading.