What is Django REST framework?

Django is a Python-based framework for building web applications, and to make it easier to create web APIs, a library called Django REST framework (also known as DRF) is added on top of Django.

REST architecture

It applies the principles of REST (Representational State Transfer), a software architecture approach for developing web services.

Setting up the Django REST framework

To start using the Django REST framework, you must first install it in your Django project.

Open your terminal and run the following command:

pip install djangorestframework

Once DRF is installed, open your project’s settings.py file and add 'rest_framework' to the INSTALLED_APPS list:

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

Creating your first API endpoint

DRF provides high-level abstractions like viewsets and serializers, which are used to create APIs and handle data serialization.

a. Serializer

The serializer provides a powerful serialization engine that allows easy conversion between Python objects and various data formats, such as .JSON, .XML, or .YAML. You can start by creating a serializer. Create a file called serializers.py and define a serializer for your Django model:

from rest_framework import serializers
from base.models import Item
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model=Item
fields = '__all__'

b. Views

With DRF, you can modify the viewset to include the desired HTTP methods for data manipulation in your views.py file.

Open your views.py file and create a viewset using the serializer:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from base.models import Item
from .serializers import ItemSerializer
@api_view(['GET'])
def getData(request):
items = Item.objects.all()
serializer = ItemSerializer(items, many=True)
return Response (serializer.data)
@api_view(['POST'])
def addItem(request):
serializer = ItemSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201) # Return the serialized data with 201 Created status
return Response(serializer.errors, status=400) # Return the validation errors with 400 Bad Request status

c. URL patterns

Finally, include the URL patterns in your urls.py file to map to the API endpoints:

from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('',include('api.urls')),
]

Authentication and Permissions

Moreover, the Django REST framework gives built-in support for authentication and permissions, along with granular permission controls to secure API endpoints.

To enable these in your project, open your settings.py file and configure the authentication classes:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}

Pagination and Filtering

Furthermore, the Django REST framework offers advanced features like pagination and filtering to optimize your API development. This allows developers to control the amount of data an API retrieves and apply filters based on query parameters.

You can modify your viewset in views.py to include pagination and filtering options:

from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import SearchFilter
from .models import YourModel
from .serializers import YourModelSerializer
class YourModelPagination(PageNumberPagination):
page_size = 10
class YourModelViewSet(viewsets.ModelViewSet):
queryset = YourModel.objects.all()
serializer_class = YourModelSerializer
pagination_class = YourModelPagination
filter_backends = [SearchFilter]
search_fields = ['field1', 'field2']

Testing and Documentation

Lastly, the DRF can automatically generate interactive API documentation, ensuring the quality and reliability of your APIs and exploring the usage of available endpoints.

In your tests.py file, write tests for your API views using Django’s testing framework and Django REST framework’s test client:

from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from .models import YourModel
class YourModelAP
ITest(APITestCase):
def setUp(self):
YourModel.objects.create(field1='Value 1', field2='Value 2')
def test_get_yourmodels(self):
url = reverse('yourmodel-list')
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), 1)

Note: The code snippets may need adjustments based on your specific project structure and requirements.

Advantages of DRF

Some of the benefits that come along with using the Django REST framework are:

  • It provides functionalities that make developing robust and scalable APIs easy.

  • It is excellent to use if you're looking to build a public API or an API to distribute data to your applications.

  • It supports building secure APIs.

  • It includes request parsing and rendering, which helps developers handle various client-server interactions with different requests and generate appropriate responses.

Conclusion

Overall, it can be concluded that the Django REST framework improves creating, testing, and managing web APIs. It supports best practices and provides comprehensive tools to ease the development process, making it a practical choice for creating APIs with Django.

"""myproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

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

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved