In this tutorial, we aim to learn best practices for building REST APIs using Django REST Framework (DRF). DRF is a powerful and flexible toolkit for building Web APIs, and it's vital to use it effectively.
You will learn:
Prerequisites:
DRF is a Django extension that provides functionalities for both client and server sides. The REST framework in DRF refers to a set of conventions for creating web services.
Use Viewsets and Routers: DRF provides a built-in system for handling different types of views. Instead of writing separate views for each CRUD operation, use ModelViewSet
or GenericViewSet
. Then, link them with a Router
to automatically generate URL patterns.
Pagination: To avoid overwhelming the client or database with data, use DRF's built-in pagination.
Filtering, Searching, and Ordering: Use DjangoFilterBackend, SearchFilter, and OrderingFilter for effective querying.
Error Handling: Always provide clear error messages and handle exceptions properly.
Testing: Test your APIs thoroughly. DRF provides a test client to simulate GET, POST, PUT, DELETE requests.
from rest_framework import viewsets
from .models import Book
from .serializers import BookSerializer
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
In the above code, BookViewSet
handles all CRUD operations. To generate URL patterns, we use a router:
from rest_framework.routers import DefaultRouter
from .views import BookViewSet
router = DefaultRouter()
router.register(r'books', BookViewSet, basename='book')
urlpatterns = router.urls
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
Here, we set the default pagination class and page size in settings.
In this tutorial, we have covered:
For next steps, consider building a full-fledged API using DRF. Refer to the official DRF documentation for more in-depth knowledge.
Exercise 1: Create a simple DRF application with a single model and use a viewset and router for CRUD operations.
Exercise 2: For the above application, implement pagination and add filters.
Solution:
The solution for Exercise 1 has been provided in Code Example 1.
For Exercise 2, add the following to your settings.py:
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10
}
And add filters in your viewset:
from rest_framework import filters
class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['title', 'author']
Keep practicing and building more complex APIs to get a solid grasp of DRF. Happy coding!