Introduction

API is an acronym for Application Programming Interface that software uses to access data(in web development) that separates 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 are 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 websites.

In this blog post, we are going to make simple Books API using 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 virtual environment, we will be using Pipenv that creates and manages virtualenv for our projects. If you already installed it skip this step otherwise you have install it through pip in command line(terminal).

pip install pipenv

 

Step 1: Setting up virtual environment and 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 first time since you have not installed it before. If you installed previously, it takes less time since it install django from caches.

Activate the environment

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

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

 

Step 2: Creating django project named Books

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

Check whether all the steps that you follow upto now is in the right path or not by simply running project with the command

python manage.py runserver

If you see the Django Welcome page, then you is good to go in the next steps.

 

Step 3: Creating new app named bookapi

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

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

settings.py

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

 

Step 4: Creating Book model inside the models.py file of bookapi app

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 Book model with fields containing title, author and description about a particular book.

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

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

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

 

Add the following line of codes in  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 super account and dump some data into the database by log into 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 From Django Admin Panel

 

Upto now, we just created a project that contains Book model inside app bookapi. We are in the halfway to complete our project. Now we have to use Django Rest Framework as discussed above into our project and converts Book model data's 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 new serializers.py file inside bookapi app

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 serializers class from rest_framework module and extend it with ModelSerializer to specify our database model Book. We assign the fields like titile, author and description to show only that fields when we call API. Overall this serializers.py file converts Book model to JSON format.

 

Step 7: Creating BookListView and BookDetailView in views.py file of bookapi app as

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 generics class from rest_framework module that extends ListAPIView in BookListView to displays all books and extends RetrieveAPIView in BookDetailView to display single book.

 

Step 8 : Setting up URL configs for API endpoints

Books > urls.py
from django.contrib import admin
from django.urls import path
from bookapi.views import BookListView, BookDetailView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', BookListView.as_view()),
    path('api/<int:pk>/', BookDetailView.as_view()),

]

We are done!!!

Run the project again 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 database Book model as

BookList From Database Using REST Framework

 

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

booklist api view raw json

 

Similarly, when you open url http://127.0.0.1:8000/api/1/ , it list the book that have id=1. We can pass 2, 3, etc. in the url and it display book with respective id's. If the id is not created in database, the API provides "Not found." message.

single book information fetch data

 

Conclusion

In this blog post, we made brand new Django project from scratch and equipped it with REST API . We created Book model to store books information in database. After that, we used Django REST Framework to make API's of Books information that could displays books list and 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 the 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:-)