Build a REST API with Django REST Framework

Building a REST API in Django is super easy. In this tutorial, we’ll walk through the steps to create your first API.

SblipDev
Geek Culture
7 min readFeb 3, 2021

--

logo of django rest framework
image from realpython.com

Why use REST API?

Before we start the fun stuff, it's good knowing why should you create an API.

A rest API is a way to provide data to other applications from our application. Those other applications can use it in any way they want. Frequently, APIs also give the application access to change the data too.

Generally, an API is a way to edit stuff in databases with requests. What you receive is a static response, mostly it is in JSON format, of whatever thing you requested.

Rest APIs are an essential skill for software development, so you must know how they work.

image from shareurcodes.com

Why Django REST Framework?

The best reason to use Django REST Framework is that it makes the hard work of serialization ultra easy!

What are we creating?

We will be creating a books API app in which we can create, read, update and delete (CRUD for short) the book entries.

Now the fun stuff.

Now we are going to create an app to test all this stuff.

Installing Django and Django rest framework

Setting up the Django project

Now, let's create the project

I am naming the Django project Books.

Now, let's go into the newly made folder ‘Books’:

Now let's create the app for our Django project.

App name is main. (sigh..)

Registering the app name in settings.py in the Books folder.

Now testing the server if it is ok or not. Run this command to start the Django server:

Ignore the warning. Image from the author

Now let’s open the given IP address http://127.0.0.1:8000/.

Image from the author

As we can see how happily Django is telling us that the web app is working, we can confirm that the server is working.

Solving migration error:

to solve the error we saw when we ran the server for the first time, we will have to run this command on the terminal.

Image from the author

Now when we run the server we won't see that error.

Creating the SuperUser

We’re about to create some models. It would be nice if we had access to Django’s beautiful and classic admin page when we want to see books in our database.

Use this command to create the all-powerful superuser.

you will be asked to fill out a few fields like below, you just answer them, note you will need to remember the username and password as we will need it.

Image from the author

To verify that it works. Let's start up the Django server and then go to this link http://127.0.0.1:8000/admin/

Now we will be welcomed with this login form.

Image from the author

You should enter the username and password that you entered in the terminal just now

After inputting the username and password, you will be greeted by this very professional admin page!

looks beautiful, doesn't it?

Creating the book model which our trustworthy Django ORM will manage

Let's create the book model!

now let's go to the models.py file in the main folder and add create the model:

We have added the book class to the models.py file.

Our book objects will contain only two fields the title of the book and its author.

Now let us register the model to the admin page in the admin.py file in the main folder.

Running the migrations (run the commands in order)

Now, let's run the server and open the admin page once again.

Now we will see one more table on the admin page called main (our app name.)

Image from the author

By clicking on books under the table called main we will see this.

Image from the author

To create a new book object we will need to click the add book button. We will need to fill out this form like below and click the save button:

Image from the author

And when we go back we will see a new object.

Image from the author

By clicking on the object you will have the options to delete and update the instance. You can create some more instances if you want.

Creating the REST API

Now, let's use Django-rest-framework to create the APIs.

let’s append rest_framework to INSTALLED_APPS dictionary.

‘…’ refers to Django's own apps

Now let's create a folder called ‘api’ in the main app folder and create new files called [‘serializer.py’, ‘urls.py’. ‘views.py’].

Folder structure by now and will remain. Image from the author

Serializing the model using ModelSerializer

Serialization is the process of converting a Model to JSON. Using a serializer, we can specify what fields should be present in the JSON representation of the model.

The serializer will turn the Book model into a JSON representation so the API user can parse them, even if they’re not using trusty python. In turn, when a user post requests JSON data to our API, the serializer will convert that JSON to a Book model for us to save or validate.

Here we pass the book model to be serialized and the fields as ‘__all__’ as we need all the fields in the rest API to be showed. ‘__all__’ also contains the id field which shows the book instance id.

Creating the rest API viewset

Paste the code below in the views.py file in the API folder,

Here we have created a viewset with passing all the instances or objects of the Book model from the database and also we have passed the serializer,

The URL work.

Adding the paths to the API urls.py file

Registering the API urls.py to project urls.py

Paste this code below.

We have now linked the API urls.py file to the main urls.py file under the Books folder.

The path to API will be ‘books/’ as in line 7

Mission Code done. Mission Testing started

Checking out and testing the API

So let's run the server and open http://127.0.0.1:8000/books/ and we will be greeted by this:

So in this URL, we are getting a list of all book instances which we created and an option to create new ones, play around with them.

When we go to this URL http://127.0.0.1:8000/books/(any instance id) we will have the option to get, delete or update (put) the instance

Option to do get, delete or put request.

Bonus!

Using the requests module to create a new book instance.

NOTE: You will need to start the server or the file will throw an error.

To install the requests module, type this in terminal:

Create a new file in any folder called requests.py or client.py and copy this code.

In the create_new_book method, we can see that we take arguments, convert them to a dictionary and post request it to http://127.0.0.1:8000/books/

And in get_all_books, it uses get request to get all book instances in a list.

And when we observe the lists of book instances, it also shows the newly added book Parallel Worlds by Michio Kaku (I recommend you should read it.)

By this, we can get the data from the server to our own python file and use it any way we want.

Farewell

I wish you had fun in this tutorial. Of course, things get more complicated in rest APIs but this is the starting point.

If you have any problem either comment on this post, I am happy to help or we have our trustworthy StackOverflow.

Ciao.

--

--

SblipDev
Geek Culture

A high schooler who loves to talk with computers in his free time and watch star wars. (https://sblip.dev)