Django REST Framework (DRF) simplifies the process of building Web APIs in Django by providing tools for serialization, handling requests, and managing views.
DRF integrates with Django by registering itself as an installed app and exposing API-specific classes like APIView and Response.
# Install Django REST Framework using pip
pip install djangorestframework
# Add DRF to installed apps
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
]
# Configure authentication, permissions, and pagination
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
],
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
}
# Simple APIView returning JSON
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class HelloWorld(APIView):
def get(self, request):
return Response({"message": "Hello, World!"}, status=status.HTTP_200_OK)
# Map API view to URL
from django.urls import path
from .views import HelloWorld
urlpatterns = [
path('hello/', HelloWorld.as_view(), name='hello-world'),
]
# Run development server
python manage.py runserver
# JSON response from API
{
"message": "Hello, World!"
}
Simulate a client consuming the DRF API Endpoint defined above: