Simple Steps to Building RESTful API with Django like abc…

Franklyn Ugege
BitHubPH
Published in
5 min readDec 30, 2019

Building API’s with Python-Django is like abc… There is a lot of abstraction though with the framework all in a bid to make development faster. In this article I would work you through building a RESTful API resource for “books”.

Let’s dive in…

Prerequisite

  • To get up and running you need to have a basic idea of programming and what RESTful APIs are.
  • You’ll need basic knowledge of Python.
  • Knowledge of databases would be a plus.
  • You’ll also need to have python installed in your machine.

Lets get started then… 😉. I’d be using a windows machine and would be making references based on that.

Step 1: Project Setup

  • Open your command prompt as an administrator.

- Click on the start menu.

- Type ‘cmd’.

- Right click on the cmd icon.

- Choose the option ‘Run as administrator’

- Choose yes on the dialog box that pops up to allow administrator make changes to your computer.

  • On the command prompt type cd / to navigate to the root of the systems directory. Take note of the space between.
  • Next create a directory with the following command mkdir books_api . This command creates a directory called books_api .
  • Navigate into this new directory to start creating your Django project by typing cd books_api command.
  • Verify that your python is installed by running python --version command to display the version of python installed. I’m using the most recent version of python at the time of this writing which is version 3.8.1.

We would be running our project in a virtual enviornment. To do that we would be using pipenv . So make sure you have pipenv installed by running checking the version with the following command pipenv --version . If it fails install pipenv with the following command pip3 install pipenv .

  • Next activate the virtual environment by runningpipenv shell
Virtual environment

Finally install django and django-restframework and create the bookapi django project.

  • To install our project dependencies in the virtual environment we would use the pipenv command: pipenv install django djangorestframework . This would create a Pipfile and Pipfile.lock which holds a record of our dependencies.
  • Finally we create the Django project: django-admin startproject bookapi . This would scarfold our project. You would notice a new directory bookapi in the book_api directory.

Step 2: App Setup

In Django, the project is seen as the entire application while the app is a module in the project. In other words we would be creating the books app for this project.

  • Navigate into the project directory by running the command cd bookapi

Here we are in the root containing manage.py : a script which allows you to run administrative tasks as we would see shortly.

  • To create our book app, run: python manage.py startapp books . This command would scarfold our new app in the bookapi project.

Not to forget, we need to register the installed apps in bookapi/bookapi/settings.py

  • Add 'rest_framework', 'books' 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',    'rest_framework',    'books',]

Step 3: Create Book Model

Open your book_api directory in your preferred code editor.

Navigate to bookapi/books/models.py and modify to contain:

from django.db import models# Create your models here.class Book(models.Model):    title = models.CharField(max_length=100)    publisher = models.CharField(max_length=100)    authors = models.CharField(max_length=256)    year = models.CharField(max_length=4)    created_at = models.DateTimeField(auto_now_add=True)

Here we define the structure of how books should be stored in our database.

Step 4: Run migrations

Migrations basically keep records of changes we make to our database structure so they can be easily reapplied. To generate the migration script run:

python manage.py makemigrations books

Next we need to apply these migrations so that the tables can be created on our database. Run

python manage.py migrate

Now we have our app setup and our database running. Note that Django has sqlite as the default setup. I am using the default in order to make this article light and easy to follow as much as possible.

Step 5: Setup Book Resource API

To create our books resource we have to setup our serializer which converts Django querysets and objects into json.

So lets get right to it… 💪

In our books app create a folder api (bookapi/books/api/)and within this folder create a serializers.py file. Add the following snippet in this file.

from rest_framework import serializersfrom books.models import Bookclass BookSerializer(serializers.ModelSerializer):    class Meta:        model = Book        fields = ("__all__")

In the snippet above we set the model to be serialized to the Book model we created earlier and finally set the returned fields to all the fields the model has.

Next we create the viewsets for the resource which acts like the controller in an MVC architecture. Like I mentioned earlier on Django is highly abstracted. With a few lines of code we can setup the CRUD functionality on the resource.

Let’s get to it… 🎺

Next we create the viewesets.py in the bookapi/books/api/ directory. Add the following snippet of code in it.

from rest_framework import viewsetsfrom .serializers import BookSerializerfrom books.models import Bookclass BookViewSets(viewsets.ModelViewSet):    queryset = Book.objects.all()    serializer_class = BookSerializer

Now, we focus on how to make the controller accessible through the routes. We’ll create a router.py file in bookapi/bookapi/ directory. Type in the code snippet in the router.py file created.

from rest_framework import routersfrom books.api.viewsets import BookViewSetsrouter = routers.DefaultRouter(trailing_slash=False)router.register('books', BookViewSets)

Our APIs are almost ready to be published. Just one final piece of step to finish it all up. Add the router created to the bookapi/bookapi/urls.py

from django.contrib import adminfrom django.urls import path, includefrom .router import routerurlpatterns = [    path('admin/', admin.site.urls),    path('api/', include(router.urls)),]

Yaay!!! ✨ ✨ ✨

Now the time of reckoning… To test the application run the app from the virtual environment with the following cli command:

python manage.py runserver

With this we have the following routes available

POST   http://localhost:8000/api/books
GET http://localhost:8000/api/books
GET http://localhost:8000/api/book/:id
DELETE http://localhost:8000/api/book/:id
PATCH http://localhost:8000/api/book/:id

Django rest framework comes with an interactive interface for the API’s created. To access it just navigate to the localhost:8000/books . There you can test out all the endpoints.

I hope this was helpful in shedding some light in how API’s are created with Python and Django.

Don’t forget to drop a comment and show appreciation by hitting the clap button 😉.

--

--

Franklyn Ugege
BitHubPH

I am a fullstack developer with extensive experience in Javascript and Python and a passion for building highly configurable and user-friendly applications