DEV Community

Harlin Seritt
Harlin Seritt

Posted on

Django Rest Framework

Easy to Build Rest APIs for your Project!

Django Rest Framework (DRF) is a powerful and flexible toolkit for building Web APIs. It is a third-party package for Django that makes it easy to build, test, and debug RESTful APIs written using the Django framework.

In this article, we will take a closer look at what DRF is, its features, and how it can be used to build RESTful APIs for your Django projects.

DRF is a package that provides a set of tools for building RESTful APIs for Django projects.

These tools include serializers, views, and routers, which are used to handle the incoming and outgoing data, as well as the routing of URLs.

DRF also includes a set of built-in authentication and permissions classes, which can be used to secure your API endpoints.

Serializers

One of the main features of DRF is its serializers. Serializers are used to convert complex data types, such as Django models, into JSON or other formats that can be easily transmitted over the web.

They also provide a way to validate incoming data and raise errors if the data is not in the expected format. Serializers can also be used to deserialize incoming data, which means that they can be used to create or update Django models from incoming data.

Views & Viewsets

Another powerful feature of DRF is its views. Views are used to handle the incoming HTTP requests and return the appropriate HTTP response.

DRF provides a set of built-in views, such as the ListAPIView and RetrieveAPIView, which can be used to handle common CRUD operations. These views can be easily customized to suit the needs of your application.

Routing

In addition to views and serializers, DRF also provides a set of tools for handling routing and URL patterns. The built-in routers can be used to automatically generate the URLs for your API endpoints, based on the views and serializers that you have defined. This makes it easy to keep your API endpoints organized and consistent.

One of the main benefits of using DRF is that it provides a consistent and well-documented way to build RESTful APIs for Django projects.

It can help you avoid the need to write a lot of boilerplate code, and also provides a number of built-in tools for handling common tasks, such as authentication and permission checking.

A Very Simple Example

To import Django Rest Framework (DRF) into your project, you need to first install it using pip, the package installer for Python. You can do this by running the following command in your terminal or command prompt:

pip install djangorestframework
Enter fullscreen mode Exit fullscreen mode

Once you have installed DRF, you will need to add it to your project's list of installed apps in the settings.py file. To do this, add 'rest_framework' to the list of apps in the INSTALLED_APPS section:

INSTALLED_APPS = [
    ...
    'rest_framework',
]
Enter fullscreen mode Exit fullscreen mode

After you've added 'rest_framework' to your INSTALLED_APPS, you'll need to run migrations to create the necessary database tables for DRF. You can do this by running the following command:

python manage.py makemigrations
python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

You also may want to add the following lines of code in the urls.py file to include the default views and viewsets provided by the package.

from rest_framework import routers
router = routers.DefaultRouter()
urlpatterns = [
    ...
    path('api/', include(router.urls)),
    path('api-auth/', include('rest_framework.urls')),
]
Enter fullscreen mode Exit fullscreen mode

With that you are ready to use all the functionalities of Django Rest Framework, in order to use it in your views, serializers and models you will need to import the appropriate classes and methods from the package.

It's worth noting that this is a basic example and depending on your project's specific requirements, you may need to make additional configurations to use all the features of the package.

A Deeper Example

Here's an example of how you might use serializers, views, and routers in Django Rest Framework (DRF) to create a simple RESTful API for a "Task" model:

# models.py
from django.db import models

class Task(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
    completed = models.BooleanField(default=False)

# serializers.py
from rest_framework import serializers
from .models import Task

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = ('id', 'name', 'description', 'completed')

# views.py
from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

# urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import TaskViewSet

router = DefaultRouter()
router.register(r'tasks', TaskViewSet)

urlpatterns = [
    path('api/', include(router.urls)),
]
Enter fullscreen mode Exit fullscreen mode

In this example, we have a simple Task model with three fields: name, description, and completed. We then define a serializer, TaskSerializer, which is used to convert the Task model into a format that can be easily transmitted over the web (in this case, JSON).

We also define a viewset, TaskViewSet, which handles the incoming HTTP requests and returns the appropriate HTTP response. The viewset is linked to the TaskSerializer and the Task model so that it can handle the CRUD operation using the serializer and model.

Finally, we use the DefaultRouter class to automatically generate the URLs for our API endpoints, based on the viewsets we have defined. The router is registered with the URL pattern 'tasks' and included in the URL pattern of the project.

Now, when you run the server (manage.py runserver) and go to the /api/tasks url, you will see the default views for the CRUD operations provided by the viewset. You can also test your endpoints with the built-in DRF's Browsable API, which allows you to test your endpoints easily from the browser.

Support, Stability, Maturity

Django Rest Framework is a mature and stable library for building RESTful APIs in Django. It has a large and active community, is well-documented and actively maintained, and is widely used in production by many companies.

It has been around since 2007 and has a large and active community of developers who contribute to its development and maintenance.

It is actively maintained and new releases come out regularly with bug fixes, security updates, and new features.

Summary

Django Rest Framework is a powerful and flexible toolkit for building RESTful APIs for Django projects.

It provides a set of tools for handling serialization, views, routing, and authentication, which can save a lot of development time and effort.

DRF also offers a consistent and well-documented way to build APIs, which helps to avoid common mistakes and also simplifies the process of building, testing and debugging APIs.

Whether you're building a simple web application or a complex system, DRF can be a valuable tool to have in your toolbox.

Top comments (0)

An Animated Guide to Node.js Event Loop

>> Check out this classic DEV post <<