How to Build RESTful APIs with Django
Building RESTful APIs is a fundamental skill for modern web developers. Django, a high-level Python web framework, provides powerful tools to create robust and scalable APIs quickly. In this guide, we’ll walk through the entire process—from setting up a Django project to deploying a fully functional RESTful API.
Why Django for RESTful APIs?
Django’s "batteries-included" philosophy makes it an excellent choice for API development. With Django REST Framework (DRF), you get:
-
Serialization – Convert complex data types (like querysets) into JSON/XML.
-
Authentication & Permissions – Built-in support for token-based auth, OAuth, and more.
-
Viewsets & Routers – Reduce boilerplate code for CRUD operations.
-
Throttling & Pagination – Control request rates and optimize responses.
Step 1: Setting Up Django
First, ensure you have Python installed. Then, create and activate a virtual environment:
bash
Copy
Download
python -m venv venv source venv/bin/activate # Linux/Mac venv\Scripts\activate # Windows
Install Django and DRF:
bash
Copy
Download
pip install django djangorestframework
Start a new Django project and app:
bash
Copy
Download
django-admin startproject apiproject
cd apiproject
python manage.py startapp api
Add rest_framework
and your app to INSTALLED_APPS
in apiproject/settings.py
:
python
Copy
Download
INSTALLED_APPS = [ ..., 'rest_framework', 'api', ]
Step 2: Creating a Model
Let’s build a simple Task API. In api/models.py
, define a Task
model:
python
Copy
Download
from django.db import models class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title
Run migrations to apply the model:
bash
Copy
Download
python manage.py makemigrations python manage.py migrate
Step 3: Serializing the Model
DRF uses serializers to convert model instances into JSON. Create api/serializers.py
:
python
Copy
Download
from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = ['id', 'title', 'completed', 'created_at']
Step 4: Building API Views
Instead of writing individual views for CRUD operations, DRF’s Viewsets simplify the process. In api/views.py
:
python
Copy
Download
from rest_framework import viewsets from .models import Task from .serializers import TaskSerializer class TaskViewSet(viewsets.ModelViewSet): queryset = Task.objects.all() serializer_class = TaskSerializer
Step 5: Configuring URLs
Use DRF’s routers to auto-generate URLs. Update apiproject/urls.py
:
python
Copy
Download
from django.contrib import admin from django.urls import path, include from rest_framework.routers import DefaultRouter from api.views import TaskViewSet router = DefaultRouter() router.register(r'tasks', TaskViewSet) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), ]
Step 6: Testing the API
Run the server:
bash
Copy
Download
python manage.py runserver
Now, visit http://127.0.0.1:8000/api/tasks/
to interact with your API. You can:
-
GET
/api/tasks/
– List all tasks. -
POST
/api/tasks/
– Create a new task. -
PUT/PATCH
/api/tasks/1/
– Update a task. -
DELETE
/api/tasks/1/
– Remove a task.
Use tools like Postman or curl for testing.
Step 7: Adding Authentication
To secure your API, DRF supports multiple authentication methods. Let’s enable Token Authentication.
First, install the required package:
bash
Copy
Download
pip install django-rest-framework-simplejwt
Update settings.py
:
python
Copy
Download
REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_simplejwt.authentication.JWTAuthentication', ], }
Add JWT routes in urls.py
:
python
Copy
Download
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ ..., path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ]
Now, only authenticated users can access the API.
Step 8: Deploying the API
For production, deploy using:
Final Thoughts
Django REST Framework simplifies API development while maintaining flexibility. By following this guide, you’ve built a secure, scalable RESTful API with minimal effort.
If you're looking to grow your YouTube channel with tech tutorials, try MediaGeneous for expert content strategies.
For further reading, check out:
Happy coding! 🚀
Top comments (0)