Django REST Framework

Ukeme Wilson
5 min readJun 25, 2024

--

If you’re looking to create robust and flexible APIs with Django, the Django REST framework (DRF) is your go-to toolkit.

Django REST framework is a powerful and flexible toolkit for building Web APIs. It simplifies the process of creating and managing APIs by providing a comprehensive suite of features.

Django REST framework adopts implementations like class-based views, forms, model validators, the QuerySet API, and more.

REST, or REpresentational State Transfer, is an architectural style for providing standards between computer systems on the web, making it easier for systems to communicate with each other.

DRF integrates with Django’s core features — models, views, and URLs — making it simple and seamless to create RESTful HTTP resources.

Some key concepts in Django rest framework includes,

Serialization:

Serialization is the process of converting complex data types, such as Django models, into native Python data types that can then be easily rendered into JSON, XML, or other content types. Also, before deserializing the data, for incoming payloads, serializers validate the shape of the data.

# serializers.py
from rest_framework import serializers
from .models import YourModel

class YourModelSerializer(serializers.ModelSerializer):
class Meta:
model = YourModel
fields = '__all__'

Views:

DRF has three different types of views:

APIView: This is a class-based view designed for building RESTful APIs, offering more control and flexibility compared to function-based views. It allows developers to define HTTP methods like GET, POST, PUT, and DELETE directly within the class, facilitating cleaner and more organized code

Generic View: This provide pre-built, reusable view classes that handle common web development tasks, such as displaying a list of objects or handling form submissions. They significantly reduce boilerplate code, enabling developers to quickly implement common functionalities by simply configuring the view with minimal code

ViewSet: A higher-level abstraction that combines the logic for handling multiple actions (such as list, create, retrieve, update, and delete) in a single class.

While Django views typically serve up HTML templates, DRF views return a JSON response.

Routers:

Routers provide an easy way of automatically determining the URL configuration for your API. They work well with ViewSets to create RESTful endpoints without much boilerplate code. They reduce repetitive code by handling the URL routing for common CRUD operations, enabling a more organized and maintainable project structure.

# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import YourModelViewSet

router = DefaultRouter()
router.register(r'yourmodels', YourModelViewSet)

urlpatterns = [
path('', include(router.urls)),
]

Filtering, Searching, and Ordering:

DRF provides a powerful framework for filtering, searching, and ordering querysets:

Filtering: Allows you to restrict the queryset based on criteria.

Searching: Adds simple search capabilities to your API.

Ordering: Provides control over the ordering of results.

pip install django-filter
INSTALLED_APPS = [   ... 
'rest_framework',
'django_filters', ]

REST_FRAMEWORK = { ...
'DEFAULT_FILTER_BACKENDS': [ 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.SearchFilter', 'rest_framework.filters.OrderingFilter', ],
}

Pagination:

DRF supports various pagination styles, allowing large querysets to be divided into smaller chunks. The built-in pagination classes include PageNumberPagination, LimitOffsetPagination, and CursorPagination.

e.g

# settings.py
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}

API Documentation:

DRF can integrate with tools like Swagger or ReDoc to provide interactive API documentation. These tools automatically generate documentation based on your API views, serializers, and models.

This can be set up using drf_yasg (Yet Another Swagger Generator) or drf_spectacular.

Testing:

DRF provides utilities for testing your API, including test cases for making requests and checking responses.

QUICK DEMO

$ pip install django
$ pip install djangorestframework

Create a project

$ django-admin startproject drf_proj .

Create an app

$ python manage.py startapp product

Edit the “settings.py” file inside the project and add “rest_framework” and “product” to the INSTALLED_APPS list

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

Set Up Model

# product/models.py
from django.db import models

# Create your models here.

class Product(models.Model):
name = models.CharField(max_length=50)
amount = models.FloatField()
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self) -> str:
return self.name

Set Up Serializer

create a new file called “serializers.py” inside the product directory

# product/serializers.py
from rest_framework import serializers
from .models import Product

class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ["id", "name", "amount", "created_at"]

Set up Views

# product/views.py
from rest_framework import viewsets
from rest_framework import permissions

from .serializers import ProductSerializer
from .models import Product

# Create your views here.

class ProductView(viewsets.ModelViewSet):

serializer_class = ProductSerializer
permission_classes = [permissions.AllowAny]
queryset = Product.objects.all()

Set up product urls.py

# product/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProductView


router = DefaultRouter()
router.register(r"product", ProductView, basename="product")

urlpatterns = [
path("", include(router.urls)),
]

Set up project urls.py

from django.contrib import admin
from django.urls import path, include

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

Next step is to set up the db

$ python manage.py makemigrations

$ python manage.py migrate

Next, we can then start the Django server

$ python manage.py runserver

Navigate to http://127.0.0.1:8000/api/product/

Using the Django rest framework interface, you can perform CRUD functionalities

Cool. This is a basic set up for Django rest framework.

Conclusion

This article dives into the different features of DRF, offering practical examples and tips to help you get started with DRF. Learn how to set up your first API endpoint, set up models, serializers and views

Ready to elevate your Django projects with RESTful APIs? Dive into our full article and start harnessing the full potential of Django REST framework today!

Let’s Get in Touch! Follow me on:

>GitHub: @bosukeme

>Linkedin: Ukeme Wilson

You can read other of my Medium Articles here

--

--