Build Powerful REST APIs with Django REST Framework - Codewolfy

Ever wondered how mobile apps fetch their data, or how different web services talk to each other? Often, it’s some form of Application Programming Interface, more commonly known as an API. In the Python ecosystem, when it comes to building robust, scalable, and secure backends, the way to go is to create a REST API using Django. The “batteries-included” philosophy of Django provides a solid ground, but, combined with a specific toolkit, it turns into an API powerhouse. In this post, we will be creating REST API using Django.

What is the Django REST Framework?

Django REST Framework, or DRF for short, is a robust, flexible, open-source toolkit written atop the Django web framework. It is intended for ease in the development of web APIs. You can think of it as a sort of specialized extension to Django that equips you with everything necessary, from serializers to authentication classes to generic views, enabling you to build APIs rapidly and efficiently by centralizing your energy on your application’s core logic instead of reinventing the wheel.

Key Benefits of Using Django REST Framework

Using DRF for your Django API has a number of significant advantages:

  • Rapid Development: DRF has ready-to-use ViewSets and Routers that handle the logic and URL generation for standard CRUD operations, thus allowing you to save countless hours of coding.
  • Powerful Serialization: It features a brilliant serialization engine which can easily convert complex data types-like Django model instances-into native Python datatypes that are then easily rendered to JSON, XML, or other content types.
  • Browsable API: One of the most loved features in DRF is the human-friendly, web-browsable API. You can interact with your API directly in the browser. Testing and debugging becomes incredibly intuitive.
  • Authentication & Permissions: Security is a priority. DRF ships with multiple inbuilt authentication policies (like OAuth1a, OAuth2, and session authentication) to control who can access or modify your API endpoints.

Building Your First Django REST API

Let’s dive in and build an API using Django for a simple Task management application. We will create endpoints to list, create, update, and delete tasks.

Project Setup and Installation

First, we need to set up our development environment. We’ll create a project folder, set up a virtual environment, and install Django and Django REST Framework. You can use any other existing application.

Navigate to directory where you want to create new Django application. Open your terminal and run the following commands to install the necessary packages:

pip install django
pip install djangorestframework

Now, create a new Django project and an app for our API:

django-admin startproject taskmanager
cd taskmanager
python manage.py startapp api

Finally, open taskmanager/settings.py and add rest_framework and your new api app to the INSTALLED_APPS list:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Third-party apps
    'rest_framework',

    # Local apps
    'api',
]

Define Your Data with a Model

A model is the blueprint for your data. In api/models.py, we will define a simple Task model. This task model will be used to manage CRUD operation for task data. We will add title, description and completed status as fields into this model.

from django.db import models

class Task(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField(blank=True, null=True)
    completed = models.BooleanField(default=False)

    def __str__(self):
        return self.title

The Serializer – Your API’s Translator

A serializer’s job is to translate our Task model instances into a format that can be easily sent over the internet, like JSON. Create a new file named api/serializers.py and add the following code:

from rest_framework import serializers
from .models import Task

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

This ModelSerializer will automatically inspect our Task model and generate the fields for our API output.

Crafting the Views with ViewSets

Views contain the logic that handles incoming requests and returns responses. DRF’s ViewSet is a magical class that combines the logic for a set of related views into a single class. It’s perfect for creating a standard CRUD API.

In api/views.py, replace the contents with this:

from rest_framework import viewsets
from .models import Task
from .serializers import TaskSerializer

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

It will provide all the required endpoints for managing task via REST API using Django REST framework.

Setting Up the URLs

Now you need to create the API endpoints or URLs. DRF’s Router works with ViewSets to automatically generate the URL patterns for us. Let’s create a new file api/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('', include(router.urls)),
]

Next, you need to include these API URLs in your main project’s taskmanager/urls.py file:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('api.urls')),
]

Running Migrations and Starting the Server

Before moving to API testing you need to run migration, which will create actual tables into your database for task model. Run below commands for migration and starting Django server.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Your development server is now running, and your Django REST API is live!

Testing Your Django REST API

You can now test your API using a tool like Postman, Insomnia, or the command-line tool curl. You can also simply visit http://127.0.0.1:8000/api/tasks/ in your browser to see DRF’s browsable API.

Let’s take a few API example for curl:

GET: all tasks:

curl -X GET http://127.0.0.1:8000/api/tasks/

POST: create a new task:

curl -X POST -H "Content-Type: application/json" -d '{"title": "Learn DRF", "description": "Finish the tutorial"}' http://127.0.0.1:8000/api/tasks/

Conclusion

You’ve successfully created a complete functioning REST API using Django and the Django REST Framework. You learned how to set up a project, define models, create serializers in order to translate the data, and use ViewSets and Routers to rapidly build out your API endpoints. This is just the beginning of your journey to develop your API in Django. From here, you will learn more advanced techniques such as authentication, permissions, filtering, and pagination, allowing you to build even more robust and secure applications.