Django is good for developing full-stack websites since it serves data and templates. What if we want to output data to a mobile app? Or create a separate frontend project from Django? This is where Django REST Framework (DRF) can help. It streamlines the operations with REST APIs in Django and makes it possible to have a separate frontend and backend. There are many ways to use the incredible power DRF provides, and, in this topic, we will start working with it.
Why DRF?
Several frameworks are available when working with REST APIs in Python or other programming languages. Each framework has its advantages and disadvantages. As you are familiar with Django, you understand that it has a reputation for being easy to develop, having one of the best ORMs, and, most importantly, being secure. By implementing DRF, you are automatically obtaining these features. Additionally, you won't have to learn a new language or framework to create APIs, making it a convenient option for developers.
Another crucial aspect is that the framework documentation is one of the best pieces of documentation available on the Internet. Finally, with DRF, you'll get the immense community support necessary for developing any software.
Installation
Enough motivation to get started, right? So, let's dig deep into the technical field!
Before starting, create and activate a virtual environment, install Django, and set up a Django project and an app. After this, you can proceed to run the framework:
pip install django-rest-frameworkAdd the rest_framework app in the installed apps list of the settings.py file.
You've installed Django Rest Framework and are ready to make a REST API with DRF. To make an API with DRF, always use at least 3 Django/DRF features: Serializers, Views, and URLs. We will break them down in the future, but we will briefly discuss them for now. It will be enough to get you started.
Serializers
When we want to send or receive data using API, the data must be in JSON format. It also applies to reception; when we receive JSON data, we need to deserialize them first. We can do these things manually by making dictionaries and dumping them into JSON, but it's inefficient. DRF serializers carry out serialization and deserialization much easier:
# serializers.py
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
"""
This is a Serializer Class that serializes the User model. If you do not understand parts of it,
is completely okay.
"""
class Meta:
model = User
fields = ['username', 'email']In the above code snippet, we have extended the Django REST Framework's ModelSerializer class. In the Meta class, we have specified that we want to use the User model, as well as the username and email fields. So, our UserSerializer class will automatically have username and email fields that grab the necessary configurations, such as uniqueness, max_length, and others from the User Model.
Views
Views in DRF resemble regular Django Views — they get requests and send responses. However, we don't need to follow the hard way. DRF has generic/class-based views determining which method to allow and which to deny. For example, if we use ListAPIView from the generics module, then we do not need to explicitly prohibit all other request methods apart from GET on the API endpoint (such as POST, PUT, PATCH, or DELETE). In combination with serializers, we can design very fast and efficient APIs. Have a look at a simple example below:
# views.py
from django.contrib.auth.models import User
from rest_framework import generics
from rest_framework import permissions
from serializers import UserSerializer
class UserListAPIView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserSerializerWe have extended ListAPIView from the generic views module of the Django Rest Framework. We have specified to serialize all users. And the UserSerializer class serializes all user objects but only their username and email as specified in the serializer class. When a GET request is made, the UserListAPIView class will return a JSON list of users.
DRF also has ViewSets that implement many functionalities simultaneously to make development easier and faster. There are ListView, CreateView, DetailView, UpdateView, and DeleteView, among many others. You'll get to know about all of them in detail later.
URLs
We can use the URL pattern as we have done so in Django. They'll work perfectly fine. However, for ViewSets, we need to use the DRF Router that creates API endpoints for all functions of a ViewSet. We'll learn more about them in the future. For now, take a look at the example:
# urls.py
from django.urls import include, path
from . import views
urlpatterns = [
path('get-user-list/', views.UserListAPIView.as_view(), name='user_list'),
]The above URL pattern is not a feature of Django Rest Framework; it's the URL pattern we use in Django. Here, we've just added a path to UserListAPIView when a request is captured at http://hostname/get-user-list/. Now, if you run the server and go to http://127.0.01:8000/get-user-list/, you'll receive a JSON with serialized data. What if we want to post data to the website? We'll talk about it soon in the topics to come!
Conclusion
Django Rest Framework is the tool that will help you develop efficient APIs with ease. And most importantly, you'll be able to do it using the familiar Django framework.
In this topic, you've seen an introduction to DRF and its core features, such as Serializers, ViewSets/Views, Routers/URLs, and others. We will continue to discuss them and their functionalities in the next topics.