Django REST Framework Examples

Explore practical examples of Django REST framework to enhance your API development skills.
By Jamie

Introduction to Django REST Framework

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.

Example 1: Creating a Simple API for a Blog

Context

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)),
]

Notes

  • Ensure you have a Post model defined in your models.py file.
  • This setup allows full CRUD operations on blog posts.

Example 2: Implementing Token Authentication

Context

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()),
]

Notes

  • Make sure to enable token authentication in your settings by adding 'rest_framework.authentication.TokenAuthentication' to your DEFAULT_AUTHENTICATION_CLASSES.
  • This example allows users to log in and retrieve their token for subsequent requests.

Example 3: Filtering and Searching API Data

Context

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)

Notes

  • Install django-filter to use the filtering feature.
  • Users can filter products by category and price, and search products by name or description.

By exploring these examples of Django REST framework example, you can enhance your understanding of how to build robust APIs using Django.