Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Viewsets and Routers in Django REST Framework

Introduction

In this tutorial, we will explore Django REST Framework's Viewsets and Routers. Viewsets provide an abstraction for handling a set of related views, while Routers help in automatically generating the URL routes for those Viewsets. By the end of this tutorial, you will be able to create and use Viewsets and Routers effectively in your Django project.

Setting Up Django REST Framework

Before we dive into Viewsets and Routers, make sure you have Django and Django REST Framework installed. You can install them using pip:

pip install django djangorestframework

Next, add 'rest_framework' to your INSTALLED_APPS in your Django settings:

INSTALLED_APPS = [
    ...
    'rest_framework',
]
                

Creating a Simple API

We'll start by creating a simple API for managing a list of books. First, create a new Django app:

python manage.py startapp books

Then, add the new app to your INSTALLED_APPS:

INSTALLED_APPS = [
    ...
    'books',
]
                

Defining the Model

Create a simple model for our books in books/models.py:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title
                

Run the migrations to create the database table:

python manage.py makemigrations
python manage.py migrate

Creating a Serializer

Next, create a serializer for the Book model in books/serializers.py:

from rest_framework import serializers
from .models import Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'
                

Using Viewsets

Create a viewset for the Book model in books/views.py:

from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer

class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
                

The ModelViewSet class provides default implementations for the standard actions (list, create, retrieve, update, destroy).

Setting Up Routers

In order to wire up our viewset, we'll use a router. Update your books/urls.py (create it if it doesn't exist):

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import BookViewSet

router = DefaultRouter()
router.register(r'books', BookViewSet)

urlpatterns = [
    path('', include(router.urls)),
]
                

Connecting to the Main URLs

Include the books app URLs in your project's main urls.py:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('books.urls')),
]
                

Now, when you run the server and navigate to /api/books/, you should see your API in action:

python manage.py runserver
[
    {
        "id": 1,
        "title": "Book Title",
        "author": "Author Name",
        "published_date": "2023-01-01"
    }
]
                

Conclusion

In this tutorial, we covered how to set up Django REST Framework, create a simple model, and use Viewsets and Routers to build an API. Viewsets and Routers help in reducing the amount of code you need to write for your API endpoints, making your codebase cleaner and more maintainable.