Django REST Framework (DRF) is a powerful toolkit for building Web APIs in Django. It provides a simple way to create and manage RESTful APIs, allowing developers to integrate their applications with various services seamlessly. This article presents three practical examples of Django REST framework to help you understand its application in real-world scenarios.
In this example, we will create a simple API for a blog application where users can view, create, and update blog posts.
from rest_framework import serializers, viewsets
from django.shortcuts import get_object_or_404
from .models import Post
# Serializer for the Post model
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Post
fields = ['id', 'title', 'content', 'created_at']
# ViewSet for the Post model
class PostViewSet(viewsets.ModelViewSet):
queryset = Post.objects.all()
serializer_class = PostSerializer
# URLs configuration
from django.urls import path, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'posts', PostViewSet)
urlpatterns = [
path('', include(router.urls)),
]
Post
model defined in your models.py
file.In this example, we will add token-based authentication to our API, allowing users to securely log in and access their data.
from rest_framework.authtoken.models import Token
from rest_framework import authentication, permissions
from rest_framework.response import Response
from rest_framework.views import APIView
class LoginView(APIView):
permission_classes = [permissions.AllowAny]
def post(self, request):
username = request.data.get('username')
password = request.data.get('password')
user = authenticate(username=username, password=password)
if user:
token, created = Token.objects.get_or_create(user=user)
return Response({'token': token.key})
return Response({'error': 'Invalid Credentials'}, status=400)
# URLs configuration
urlpatterns += [
path('login/', LoginView.as_view()),
]
'rest_framework.authentication.TokenAuthentication'
to your DEFAULT_AUTHENTICATION_CLASSES
.This example demonstrates how to implement filtering and searching on a list of products in an e-commerce application.
from rest_framework import viewsets, filters
from django_filters.rest_framework import DjangoFilterBackend
from .models import Product
from .serializers import ProductSerializer
class ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
filter_backends = [DjangoFilterBackend, filters.SearchFilter]
filterset_fields = ['category', 'price']
search_fields = ['name', 'description']
# URLs configuration
router.register(r'products', ProductViewSet)
django-filter
to use the filtering feature.By exploring these examples of Django REST framework example, you can enhance your understanding of how to build robust APIs using Django.