In episode 6, we had serializers turning the Category and Transaction models into JSON. This episode turns them into a complete CRUD REST API: with just two ViewSet classes and one Router, you get endpoints for listing, detail, creating, updating, and deleting transactions — proper REST without hand-writing every view.

Step 1: Install DRF and register the app

If it’s not installed yet, add Django REST Framework to the project and register it in settings.py:

pip install djangorestframework
# config/settings.py
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"rest_framework",
"expenses",
]

Step 2: Write the ViewSets for Category and Transaction

A ModelViewSet bundles the 5 list, create, retrieve, update, and destroy actions into a single class. Note the select_related("category") right from the start to avoid the N+1 query problem when serializing the transaction list:

# expenses/views.py
from rest_framework import viewsets
from .models import Category, Transaction
from .serializers import CategorySerializer, TransactionSerializer
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.all().order_by("name")
serializer_class = CategorySerializer
class TransactionViewSet(viewsets.ModelViewSet):
queryset = Transaction.objects.select_related("category").order_by("-date")
serializer_class = TransactionSerializer

Step 3: Register the router and wire up URLs

The router auto-generates all standard REST URLs from the ViewSets. Two registration lines and the whole API is ready:

# expenses/urls.py
from django.urls import include, path
from rest_framework import routers
from .views import CategoryViewSet, TransactionViewSet
router = routers.DefaultRouter()
router.register(r"categories", CategoryViewSet)
router.register(r"transactions", TransactionViewSet)
urlpatterns = [
path("api/", include(router.urls)),
]

Then connect expenses.urls to the project’s root urls.py with path("", include("expenses.urls")). The two router.register() lines above automatically generate these endpoints: GET /api/transactions/ (list), POST /api/transactions/ (create), GET /api/transactions/1/ (detail), PUT/PATCH /api/transactions/1/ (update), and DELETE /api/transactions/1/ (delete) — the same for categories.

Step 4: Try the API

python manage.py runserver
curl http://127.0.0.1:8000/api/transactions/

Open your browser at http://127.0.0.1:8000/api/ and you’ll see DRF’s Browsable API interface: the endpoint list plus forms to try POST/PATCH directly, no Postman needed yet. The sample data seeded in episode 4 will show up immediately if you ran loaddata earlier.

Apply It to Your Project

Once the API works, any frontend (React, Flutter, or even the admin site) can call the same set of endpoints. Keep this habit from now on: every queryset in a ViewSet ships with select_related/prefetch_related for the relations you use often, and let the router handle URLs instead of declaring them manually — episode 10 will come back to extend this very endpoint set with pagination, filtering, and search.

Related Posts

Frequently Asked Questions

How is a ViewSet different from a plain APIView?

APIView forces you to hand-write each get/post method for each URL. ModelViewSet bundles the 5 standard CRUD actions, and the router generates the URLs — a fit for 90% of data-management endpoints like categories and transactions.

What is the basename parameter in router.register() for?

When a ViewSet has a queryset, the router infers the basename from the model to name URLs (e.g. transaction-list). You only need to pass basename manually when the ViewSet has no queryset (uses a dynamic get_queryset()).

Why use select_related in the ViewSet queryset?

The Transaction serializer usually also reads the category name. Without select_related, each record in the list causes one extra query — a 100-transaction page becomes 101 queries. Bundle it from the start and the API is both fast and easy on the database.

What if I want a view-only endpoint, no create/update/delete?

Swap ModelViewSet for ReadOnlyModelViewSet — the router still generates all URLs but only GET list and detail remain; write methods automatically return 405. This is common for public stats endpoints, like the one we’ll build in episode 11.

References