Using DefaultRouter and SimpleRouter

Introduction

In Django Rest Framework (DRF), routers provide an easy and consistent way to automatically generate URL patterns for your API. Two commonly used routers are DefaultRouter and SimpleRouter. This tutorial will guide you through using both DefaultRouter and SimpleRouter with a practical use case and detailed explanations.

Prerequisites

Before you start, ensure you have a DRF project set up. If not, please refer to our previous tutorial on setting up a DRF project.

What are Routers?

Definition

Routers in DRF simplify the process of configuring URL patterns for your API. They automatically generate URL patterns based on the ViewSets you define, making your code more maintainable and less error-prone.

Types of Routers

  • DefaultRouter: Provides routes for standard CRUD operations and includes a default API root view.
  • SimpleRouter: Similar to DefaultRouter but does not include the default API root view.

Using DefaultRouter

Example Use Case: Simple Library System

Let’s create a simple API to manage books and authors using DefaultRouter.

Step 1: Define the Models

# myapp/models.py

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    birthdate = models.DateField()

    def __str__(self):
        return self.name

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE)
    published_date = models.DateField()

    def __str__(self):
        return self.title

Step 2: Create Serializers

# myapp/serializers.py

from rest_framework import serializers
from .models import Author, Book

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ['id', 'name', 'birthdate']

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ['id', 'title', 'author', 'published_date']

Step 3: Define ViewSets

# myapp/viewsets.py

from rest_framework import viewsets
from .models import Author, Book
from .serializers import AuthorSerializer, BookSerializer

class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

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

Step 4: Configure URLs with DefaultRouter

# myapp/urls.py

from rest_framework.routers import DefaultRouter
from .viewsets import AuthorViewSet, BookViewSet

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

urlpatterns = router.urls

Include the app’s URLs in the project’s main urls.py file:

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

Step 5: Run the Development Server

Run the Django development server to test your setup:

python manage.py runserver

Step 6: Test the API

You can use tools like Postman or curl to test your API.

Example Requests

1. Create an Author:
curl -X POST http://127.0.0.1:8000/api/authors/ -H "Content-Type: application/json" -d '{
    "name": "J.K. Rowling",
    "birthdate": "1965-07-31"
}'
2. Get Author List:
curl -X GET http://127.0.0.1:8000/api/authors/
3. Create a Book:
curl -X POST http://127.0.0.1:8000/api/books/ -H "Content-Type: application/json" -d '{
    "title": "Harry Potter and the Philosopher\'s Stone",
    "author": 1,
    "published_date": "1997-06-26"
}'
4. Get Book List:
curl -X GET http://127.0.0.1:8000/api/books/

Using SimpleRouter

Example Use Case: Simple Library System

Let’s create the same API to manage books and authors using SimpleRouter.

Step 1: Define the Models

Same as the DefaultRouter example above.

Step 2: Create Serializers

Same as the DefaultRouter example above.

Step 3: Define ViewSets

Same as the DefaultRouter example above.

Step 4: Configure URLs with SimpleRouter

# myapp/urls.py

from rest_framework.routers import SimpleRouter
from .viewsets import AuthorViewSet, BookViewSet

router = SimpleRouter()
router.register(r'authors', AuthorViewSet)
router.register(r'books', BookViewSet)

urlpatterns = router.urls

Include the app’s URLs in the project’s main urls.py file:

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

Step 5: Run the Development Server

Run the Django development server to test your setup:

python manage.py runserver

Step 6: Test the API

You can use tools like Postman or curl to test your API.

Example Requests

Same as the DefaultRouter example above.

Advantages and Disadvantages

Feature DefaultRouter SimpleRouter
API Root View Includes a default API root view Does not include a default API root view
Automated URL Routing Yes Yes
Complexity Slightly more complex due to additional features Simpler, with fewer features
Use Case Suitable for projects that benefit from a root view Suitable for projects that do not need a root view

What is a Root View?

A Root View in Django Rest Framework (DRF) serves as an entry point for the API. It provides an overview of all the available endpoints and their corresponding URLs. This can be especially useful for developers as it offers a clear structure of the API and facilitates easier navigation.

Characteristics of a Root View:

  1. Overview: Lists all the available endpoints in the API.
  2. Navigation: Allows developers to quickly see the available resources and navigate to specific endpoints.
  3. Documentation: Acts as a form of documentation, showing the structure of the API and the endpoints provided by the application.

DefaultRouter and Root View

In DRF, the DefaultRouter automatically generates a root view. This root view lists all the registered routes in a single place, making it easier to understand the API’s structure.

Example of a Root View with DefaultRouter:

/api/
/api/authors/
/api/books/

Each of these entries would be a hyperlink to the respective endpoint, providing a clear map of the API.

SimpleRouter and Root View

In contrast, the SimpleRouter does not include a root view. It still provides automatic URL routing for ViewSets but does not generate a summary of available endpoints. This makes SimpleRouter a simpler, more lightweight option when a root view is not necessary.

When to Use Each Router

  • Use DefaultRouter: When you need a comprehensive overview of all API endpoints. This is particularly useful for large APIs with many endpoints or when the API is being used by other developers who need to quickly understand the available resources.
  • Use SimpleRouter: When you want to keep things minimal and do not need an auto-generated overview of endpoints. This can be suitable for smaller projects or internal APIs where the structure is already well-understood by the developers.

Conclusion

Using DefaultRouter and SimpleRouter in Django Rest Framework provides a powerful and efficient way to manage URLs for your API. DefaultRouter includes a default API root view, while SimpleRouter does not. By understanding how to use these routers and their respective advantages and disadvantages, you can create a well-structured and maintainable API with minimal code.


Tags: Using DefaultRouter and SimpleRouter in Django Rest Framework, DRF router tutorial, how to use DefaultRouter and SimpleRouter in DRF, Django API development