Create Simple REST API with Django

Introduction

API is an acronym for Application Programming Interface that software uses to access data(in web development) that separates the back end from the front end.

Representational State Transfer (REST) is an architectural style for an application program interface (API) first proposed in 2000 by Roy Fielding in his dissertation thesis. It is an approach to building APIs on top of the web, which means on top of the HTTP protocol.

Every Restful API is stateless, supports common HTTP verbs (GET, POST, PUT, DELETE, etc.), and returns data either in JSON or XML formats.

Django is not just the Python Web Development Framework but also the most powerful toolkit for building Web APIs. It is used for making back-end API for large companies like Instagram, Disqus, etc. rather than just a monolithic website.

In this blog post, we are going to make simple Books API using the Django REST Framework package. There are lots of packages in Django for creating APIs but Django REST Framework is the most powerful, flexible, mature, full of features, customizable, testable, and extremely well-documented that transforms any existing Django application into a web API.

 

Implementation

Now let’s begin our coding part. I assumed that you have already installed Python 3 in your operating system.

For creating a virtual environment, we will be using Pipenv which creates and manages virtualenv for our projects. If you already installed it skip this step otherwise you have installed it through pip in the command line(terminal).

pip install pipenv

 

Step 1: Set up virtualenv & install Django

C:\>mkdir Books
C:\>cd Books
C:\Books>pipenv install django

When you run this command it takes some time to install Django if it is the first time since you have not installed it before. If you installed it previously, it takes less time since it installs Django from caches.

Activate the environment

C:\Books>pipenv shell
(Books-8Au-9fUW) C:\Books>

When we run pipenv shell, Pipenv activates a virtual environment that is named from the working directory where we activated it. As we can see additional random values are attached to the working directory name this is to create a unique mapping between our projects and the virtual environment.

 

Step 2: Creating a Django project named Books

(Books-8Au-9fUW) C:\Books>django-admin startproject Books

Check whether all the steps that you follow up to now are on the right path or not by simply running a project with the command.

python manage.py runserver

If you see the Django welcome page, then you are good to go in the next steps.

 

Step 3: Create a new app

(Books-8Au-9fUW) C:\Books>django-admin startapp bookapi

Then add the new app bookapi at the bottom of the INSTALLED_APPS  configuration of the settings.py file of our project as:

settings.py

INSTALLED_APPS = [
    ...........
    ...........
    
    # local apps
    'bookapi.apps.BookapiConfig',
]

Step 4: Create Book model

bookapi > models.py

from django.db import models


class Book(models.Model):
    title = models.CharField(max_length=50)
    author = models.CharField(max_length=50)
    description = models.TextField(max_length=500)

    def __str__(self):
        return self.title

Here we create a Book model with fields containing the title, author, and description of a particular book.

Now, migrate changes in the database with the following command:

(Books-8Au-9fUW) C:\Books>python manage.py makemigrations bookapi

(Books-8Au-9fUW) C:\Books>python manage.py migrate

 

Add the next line of codes in the admin.py  file inside bookapi app

bookapi > admin.py

from django.contrib import admin
from .models import Book

admin.site.register(Book)

After that create a super account and dump some data into the database by logging into the admin panel as:

(Books-8Au-9fUW) C:\Books>python manage.py createsuperuser

Open the link http://127.0.0.1:8000/admin/ in your browser and upload some data as:

data-upload-books-model

Up to now, we just created a project that contains a Book model inside the app bookapi. We are halfway to completing our project. Now we have to use Django Rest Framework as discussed above in our project and convert Book model data into JSON format.

 

Step 5: Install djangorestframework

(Books-8Au-9fUW) C:\Books>pipenv install djangorestframework

 

Then, add rest_framework to the  INSTALLED_APPS  config as:

settings.py

INSTALLED_APPS = [
    .........

    # third party
    'rest_framework',

    # local apps
    'bookapi.apps.BookapiConfig',
]

Step 6: Creating a serializers

bookapi > serializers.py

from rest_framework import serializers
from .models import Book


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('title', 'author', 'description')

Above, we import the serializers class from the rest_framework module and extend it with ModelSerializer to specify our database model Book. We assign the fields like title, author, and description to show only those fields when we call API. Overall this serializers.py file converts the Book model to JSON format.

 

Step 7: Creating BookListView and BookDetailView

bookapi > views.py

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer


class BookListView(generics.ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(generics.RetrieveAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

We import the generics class from the rest_framework module that extends ListAPIView in BookListView to display all books and extends RetrieveAPIView in BookDetailView to display a single book.

 

Step 8: Setting up URL configs

Books > urls.py

from rest_framework import generics
from .models import Book
from .serializers import BookSerializer


class BookListView(generics.ListAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


class BookDetailView(generics.RetrieveAPIView):
    queryset = Book.objects.all()
    serializer_class = BookSerializer

We are done!!!

Rerun the project and open the following URLs in your browser and see the magic!!!

python manage.py runserver

 

http://127.0.0.1:8000/api/ ⇒ When you open this URL, it will list out all the books that we created from the database Book model as:

booklist-api-view

When you click on the “GET” button in the upper right corner and select JSON, you will see the raw JSON as:

booklist-api-view-raw-json

Similarly, when you open the URL http://127.0.0.1:8000/api/1/, it lists the book that has id=1. We can pass 2, 3, etc. in the URL and it displays the book with respective IDs. If the id is not created in the database, the API provides a “Not found.” message.

bookdetail-api-view

Conclusion

In this blog post, we made a brand new Django project from scratch and equipped it with REST API. We created a Book model to store book information in the database.

After that, we used Django REST Framework to make an API of Books information that could display a book list and a single book in the “GET” request.

We understood how the serializers.py file converts the Django model into JSON format. If you have any problem during this time, please leave a reply in the comment section, I will hear asap and if you like this post, share it with your friends.

 

Reference

Django for APIs by William S. Vincent

Happy Learning:-)

Leave a Comment