Wednesday, November 5, 2025

thumbnail

Using Django REST Framework for Building APIs

 ๐Ÿงฉ Using Django REST Framework (DRF) for Building APIs

๐Ÿ’ก 1. What Is Django REST Framework?


Django REST Framework (DRF) is a high-level library built on Django that simplifies creating RESTful APIs.

It provides ready-to-use components for:


Serialization (converting data to and from JSON)


Authentication & Permissions


Routing and URL handling


Browsable API interface (interactive API web UI)


๐Ÿง  DRF turns Django into a full-featured API backend without reinventing the wheel.


⚙️ 2. Why Use DRF?

Feature Benefit

Serialization Easily convert Django models to JSON and back

Browsable API Auto-generated, user-friendly interface for testing

Authentication Supports Token, Session, OAuth2, JWT, etc.

Permissions Control access at user or object level

Pagination, filtering, versioning Built-in tools for scalability

Integration with Django ORM Work seamlessly with your models


๐Ÿ” DRF helps developers focus on logic — not boilerplate code.


๐Ÿงฐ 3. Setting Up a Django REST Framework Project

Step 1: Install Dependencies

pip install django djangorestframework


Step 2: Create a New Django Project

django-admin startproject myapi

cd myapi

python manage.py startapp users


Step 3: Add to settings.py

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'rest_framework',  # Add DRF

    'users',           # Our app

]


๐Ÿงฑ 4. Creating a Simple API


Let’s build a User API as an example.


models.py (in users/)

from django.db import models


class User(models.Model):

    name = models.CharField(max_length=100)

    email = models.EmailField(unique=True)

    date_joined = models.DateTimeField(auto_now_add=True)


    def __str__(self):

        return self.name



Run migrations:


python manage.py makemigrations

python manage.py migrate


๐Ÿ“ฆ 5. Serializers — Converting Models to JSON

serializers.py (in users/)

from rest_framework import serializers

from .models import User


class UserSerializer(serializers.ModelSerializer):

    class Meta:

        model = User

        fields = '__all__'



๐Ÿง  Serializers define how model instances are transformed into JSON and validated when creating/updating.


๐Ÿš€ 6. Views — The Logic Layer


DRF offers several view types:


APIView — manually handle requests (fine-grained control)


Generic Views — prebuilt views for common CRUD operations


ViewSets — automatic route handling with routers


Let’s use a ViewSet for simplicity.


views.py

from rest_framework import viewsets

from .models import User

from .serializers import UserSerializer


class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all()

    serializer_class = UserSerializer


๐ŸŒ 7. URLs and Routing

urls.py (in users/)

from django.urls import path, include

from rest_framework.routers import DefaultRouter

from .views import UserViewSet


router = DefaultRouter()

router.register(r'users', UserViewSet)


urlpatterns = [

    path('', include(router.urls)),

]


Add to the project’s myapi/urls.py

from django.contrib import admin

from django.urls import path, include


urlpatterns = [

    path('admin/', admin.site.urls),

    path('api/', include('users.urls')),

]


๐Ÿงญ 8. Run the API Server

python manage.py runserver



Visit:


http://127.0.0.1:8000/api/users/

 — Browsable API view


http://127.0.0.1:8000/api/users/1/

 — Retrieve a specific user


You can use the DRF web interface to GET, POST, PUT, or DELETE data interactively!


๐Ÿ” 9. Adding Authentication and Permissions

In settings.py

REST_FRAMEWORK = {

    'DEFAULT_AUTHENTICATION_CLASSES': [

        'rest_framework.authentication.SessionAuthentication',

        'rest_framework.authentication.TokenAuthentication',

    ],

    'DEFAULT_PERMISSION_CLASSES': [

        'rest_framework.permissions.IsAuthenticated',

    ]

}



To enable Token Authentication:


pip install djangorestframework-simplejwt



Then configure JWT in settings.py and your routes. DRF will then require valid tokens for accessing endpoints.


๐Ÿงฉ 10. Advanced DRF Features

Feature Description

Filtering & Searching Use django-filter to filter querysets

Pagination Add pagination globally or per view

Throttling Rate-limit API requests

Versioning Support multiple API versions easily

Documentation Auto-generate API docs using DRF’s schema or Swagger (drf-yasg)


Example for filtering:


from rest_framework import filters


class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all()

    serializer_class = UserSerializer

    filter_backends = [filters.SearchFilter]

    search_fields = ['name', 'email']



Now you can search like:

/api/users/?search=Alice


⚡ 11. Benefits of Using DRF


Minimal boilerplate compared to raw Django views.


Built-in security and permission management.


Scales easily for large applications.


Great developer experience with the browsable API.


Easy integration with frontend frameworks (React, Vue, etc.).


๐Ÿงฑ DRF is the bridge between powerful Django models and modern RESTful APIs.


๐Ÿงญ 12. Example Folder Structure

myapi/

├── myapi/

│   ├── settings.py

│   ├── urls.py

├── users/

│   ├── models.py

│   ├── views.py

│   ├── serializers.py

│   ├── urls.py

└── manage.py


๐Ÿงฉ 13. Conclusion


Django REST Framework provides a complete, elegant, and production-ready toolkit for building RESTful APIs in Python.

It abstracts the repetitive work while maintaining Django’s strengths: scalability, security, and simplicity.


๐Ÿš€ With DRF, you can go from a Django model to a fully functional, documented REST API in minutes.

Learn Fullstack Python Training in Hyderabad

Read More

How to Build a RESTful API with Flask

Introduction to REST APIs with Python

Building APIs with Python

Encrypting Sensitive Data in Full Stack Python Apps

At Our Quality Thought Training Institute in Hyderabad

Get Directions


Subscribe by Email

Follow Updates Articles from This Blog via Email

No Comments

About

Search This Blog

Powered by Blogger.

Blog Archive