Django REST Framework (DRF) is a powerful and flexible toolkit for building Web APIs with Django. It simplifies API development by providing serialization, authentication, permissions, and built-in views.
In this guide, we’ll cover:
- Installing Django and DRF
- Creating a Django project
- Setting up a REST API with DRF
- Implementing CRUD operations
- Adding authentication
1. Installing Django and DRF
Ensure you have Python installed, then install Django and DRF:
pip install django djangorestframework
2. Creating a Django Project and App
Create a new Django project and an app for our API:
django-admin startproject myproject
cd myproject
django-admin startapp myapp
Add 'rest_framework'
and 'myapp'
to INSTALLED_APPS
in settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework', # Django REST Framework
'myapp', # Our app
]
Run migrations:
python manage.py migrate
3. Setting Up a Django REST API
We’ll create an API for managing users with CRUD (Create, Read, Update, Delete) operations.
3.1 Defining the User Model
In myapp/models.py, define a User
model:
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField(unique=True)
age = models.IntegerField()
def __str__(self):
return self.name
Apply migrations:
python manage.py makemigrations myapp
python manage.py migrate
4. Serializing the Model
DRF uses serializers to convert model instances to JSON.
Create myapp/serializers.py:
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
5. Creating API Views
DRF supports multiple types of views. We’ll use Class-based API views.
Create myapp/views.py:
from rest_framework import generics
from .models import User
from .serializers import UserSerializer
class UserListCreateView(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
ListCreateAPIView
allows GET (list all users) and POST (create a user).RetrieveUpdateDestroyAPIView
allows GET, PUT, PATCH, and DELETE on a specific user.
6. Defining URL Patterns
Create myapp/urls.py:
from django.urls import path
from .views import UserListCreateView, UserDetailView
urlpatterns = [
path('users/', UserListCreateView.as_view(), name='user-list'),
path('users/<int:pk>/', UserDetailView.as_view(), name='user-detail'),
]
Include the app URLs in myproject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('myapp.urls')),
]
Run the development server:
python manage.py runserver
Test the API at:
GET /api/users/
– List all usersPOST /api/users/
– Create a userGET /api/users/<id>/
– Retrieve a userPUT /api/users/<id>/
– Update a userDELETE /api/users/<id>/
– Delete a user
7. Adding Authentication
Modify settings.py to enable authentication:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
}
Install Token Authentication:
pip install djangorestframework-simplejwt
Add JWT authentication to settings.py:
REST_FRAMEWORK['DEFAULT_AUTHENTICATION_CLASSES'].append(
'rest_framework_simplejwt.authentication.JWTAuthentication'
)
Run migrations:
python manage.py migrate
Create a view for user authentication:
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from django.urls import path
urlpatterns += [
path('token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
Test authentication:
- Get a token (
POST /api/token/
) with:
{
"username": "admin",
"password": "password"
}
- Use the token in requests:
- Add
Authorization: Bearer <token>
in headers.
- Add
8. Browsable API
DRF provides a browsable API. Add this to INSTALLED_APPS:
'rest_framework.authtoken'
Run:
python manage.py createsuperuser
Log in at /admin/
and explore API at /api/