Django for APIs Notes - Part IV
Django for APIs is a project-based guide to building modern APIs with Django & Django REST Framework.
Django for APIs is a project-based guide to building modern APIs with Django & Django REST Framework. It is suitable for beginners who have never built an API before as well as professional programmers looking for a fast-paced introduction to Django fundamentals and best practices.
These are essential notes and code snippets from the book that help in extending any existing Django website into web API with minimal effort, covering everything from scratch to hosting and API documentation. We'll be discussing viewsets and routers in Django Rest Framework in Part IV.
Viewsets and Routers
Viewsets and routers are tools within the Django REST Framework that can speed-up API development. They are an additional layer of abstraction on top of views and URLs.
The primary benefit is that a single viewset can replace multiple related views. And a router can automatically generate URLs for the developer.
Note: By using
get_user_model we ensure that we are referring to the correct user model, whether it is the default User or a custom user model as is often defined in new Django projects.
A viewset is a way to combine the logic for multiple related views into a single class. In other words, one viewset can replace multiple views.
The tradeoff is that there is a loss in readability for fellow developers who are not intimately familiar with viewsets. So it’s a trade-off.
from django.contrib.auth import get_user_model
from rest_framework import viewsets
from .serializers import UserSerializer
class UserViewSet(viewsets.ModelViewSet): # new
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
Routers work directly with viewsets to automatically generate URL patterns for us.
Django REST Framework has two default routers: SimpleRouter and DefaultRouter.
from django.urls import path
from rest_framework.routers import SimpleRouter
from .views import UserViewSet
router = SimpleRouter()
router.register('users', UserViewSet, base_name='users')
urlpatterns = router.urls
A good rule of thumb is to start with views and URLs. As your API grows in complexity if you find yourself repeating the same endpoint patterns over and over again, then look to viewsets and routers. Until then, keep things simple.
Find more about it on GitHub.
Intern @BrightMoney | Ex-SDE Intern @DPhi | MLH Fellow | Ex DSC Lead | InOut 7.0 Winner | SIH2020 Winner | Full Stack Web Developer