Tutorial Basic Django REST Framework.

DRF logo

REST is one of the methods we usually use in creating API’s. One of the advantages of REST in Django is that we can make it quickly and easily. So, we can deploy our Django apps as soon as possible.

There is a library for Django named “Django REST Framework (DRF)” that we can use for developing REST API.

DRF requires the following:

  • Python (3.5, 3.6, 3.7)
  • Django (1.11, 2.0, 2.1, 2.2)

DRF recommend and only officially support the latest patch release of each Python and Django series.

Now, we will create a simple application to implement REST in Django.

Initial Preparation.

  • Make sure virtualenv and pip has been configured well.
  • Install Django with pip: pip install Django.
  • Create a new project with django-admin startproject drf_project .. Note: drf_project is my project name. You can use another project name.

Install DRF.

  • We can install DRF with pip install djangorestframework.
  • Add rest_framework to INSTALLED_APPS in drf_project/settings.py file.
INSTALLED_APPS = (
	# Other apps
	'rest_framework',
)
  • We can use browsable API to our application. Modify the root urls.py as below.
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers

router = routers.DefaultRouter()

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

Run Our Project.

  • We need to migrate default migration to database with python manage.py migrate. Note: I use default sqlite3 as database. You can set custom database as you want.
  • Create a superuser with python manage.py createsuperuser. Then fill the credential as you want.
  • Run our django project with python manage.py runserver.
  • Open your browser then type localhost:8000/api/.

Default API root view

Create an Example Application.

We will create an application called books application. The books application have two models, Author and Book.

  • Create a new application with django-admin startapp books drf_project/books/. Note: I usually put the application inside of project folder.

Tree of project directory

  • Add drf_project.books to INSTALLED_APPS in drf_project/settings.py file.
INSTALLED_APPS = (
	# Other apps
	‘rest_framework’.
	‘drf_project.books’,
)
  • Modify drf_project/books/models.py as below.
from django.db import models


# Create your models here.
class Author(models.Model):
    name = models.CharField(max_length=100, verbose_name="Name")

    def __str__(self):
        return self.name


class Book(models.Model):
    title = models.CharField(max_length=100, verbose_name="Title")
    description = models.TextField(verbose_name="Description")
    author = models.ForeignKey(Author, related_name='books', on_delete=models.CASCADE, verbose_name="Author")

    def __str__(self):
        return self.title
  • Run makemigrations with python manage.py makemigrations books.
  • Run migrate with python manage.py migrate.
  • Create a serializer file named drf_project/books/serializers.py. Serializer used for representing data in JSON. Serializer usually uses based on a model but it also can use without a model. Check https://www.django-rest-framework.org/api-guide/serializers/ for another reference about serializer.
  • Modify drf_project/books/serializers.py as below.
from rest_framework import serializers

from .models import Author, Book


class AuthorSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Author
        fields = ('name',)


class BookSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Book
        fields = ('title', 'description', 'author')
from rest_framework import viewsets

from .models import Author, Book
from .serializers import AuthorSerializer, BookSerializer


# Create your views here.
class AuthorViewSet(viewsets.ModelViewSet):
    queryset = Author.objects.all()
    serializer_class = AuthorSerializer


class BookViewSet(viewsets.ModelViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer
  • Modify drf_project/urls.py as below.
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers

from drf_project.books import views as books_views

router = routers.DefaultRouter()
router.register('authors', books_views.AuthorViewSet)
router.register('books', books_views.BookViewSet)

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

Test Our API.

We need to test our API to ensure that API will work as expected. We can test our API with Django browsable API.

  • Run our django project with python manage.py runserver.
  • Open your browser then type localhost:8000/api/.

API root view

API author list

API book list

As you can see in the pictures above. You can browse API from browser and insert data via an available form. You can test API with other tools like Postman or via cURL.

  • Add pagination to control how many objects per page are returned. To enable, add the following lines to drf_project/settings.py file.
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}

API author list with data

That’s it. If you have a question, please write in comments section. Thanks for reading. See you.

Reference: https://www.django-rest-framework.org/

Read: Install Odoo 12 and Wkhtmltopdf on Ubuntu 18.04 or Debian 9

Comments