Quick Build REST API with Django REST Framework

Andika Pratama
6 min readAug 20, 2022

--

In the previous article I explained how to create a fully functional e-commerce website using the Django framework. Now I will show you how to create a REST API using the Django Framework. To create a REST API using Django we will use a toolkit called Django REST Framework (DRF).

For Reminder What is Django ?

Django is a open source high-level Python Web framework that encourages rapid development and clean, pragmatic design.

What is Django REST Framework (DRF) ?

Is a powerful and flexible toolkit for building Web APIs. It will elegantly handles data serialization and seamlessly works with Django’s ORM. For complete documentation, please refer to the following link:

django-rest-framework.org

In this tutorial we are going to look at how to use DRF to create a very simple Product Item REST API for online store. I will be assuming you are already familiar with Django models and REST.

We will make sure that our REST API will be accessible by following HTTP method :

  • GET, serves to read data/resources from the REST server
  • POST, serves to create a new data/resource on the REST server
  • PUT, serves to update data/resources on the REST server
  • DELETE, serves to delete data/resources from the REST server
  • OPTIONS, serves to get supported operations on resources from the REST server.

According to me there are 5 total steps to create REST API with Django :

  1. Install and setup Django Rest Framework
  2. Set up Django Models
  3. Set up Serializers
  4. Set up ViewSet and Route URLs
  5. Testing API with HTTP method

1. Install and Setup Django Rest Framework (DRF)

Before we install Django REST Framework on your device, we start by creating a virtual environment. For this example I use venv module with python 3 to create my virtual environment.

  • Windows
=== create virtual environment named "drf_env" ===
c:\>python -m venv drf_env
=== activate virtual environment ===
c:\>source drf_env/Scripts\activate.bat
  • Linux or Mac OS
=== create virtual environment named "drf_env" ===
$ python3 -m venv drf_env
=== activate virtual environment ===
$ . drf_env/bin/activate

If you do not want to use venv module, you can use another tools to make virtual environment like Anaconda. I’m sure there are many tutorials to help you create one.

After the virtual environment is created and activated, let’s install django and djangorestframework.

(drf_env) $ pip install django(drf_env) $ pip3 install djangorestframework

And then after installing the necessary requirements let’s create a Django project and app.

=== Create django project named "my_rest_api" ===
(drf_env) $ django-admin startproject my_rest_api
=== Go to the project directory that has been created ===
(drf_env) $ cd my_rest_api
=== Create django app named "product_api" ===
(drf_env) $ python manage.py startapp product_api

After the app is created, let’s register the app by adding the path to the app config in the my_rest_api/settings.py And we should also add rest_framework to this list.

Finally make sure the app is up and running by using the Django runserver command.

python manage.py runserver

2. Set up Django Models

In this step we will make our Django models for REST API in product_api/models.py file. In this example we make two model with name Category and Item to represent a product in an online store.

In this case I use a database called SQLite, which is the default database used after installing Django. If you want to change using MySQL , please replace Database setting in my_rest_api/settings.py with this code:

DATABASES = {
'default': {
'NAME': 'your_db_name',
'ENGINE': 'django.db.backends.mysql',
'HOST': '127.0.0.1',
'USER': 'your_db_username',
'PASSWORD': 'your_db_password',
'PORT': '3306'
}
}

After that let’s run the migrations to add 2 new tables to the database.

(drf_env) $ python manage.py makemigrations(drf_env) $ python manage.py migrate

3. Set up Serializers

Now that we have the models, it is time to create serializers for the models. The serializers will convert the Category model and Item model into JSON encoding format that will be used by the API to return the data. We will add the serializers by creating a new file in product_api/serializers.py.

4. Set up ViewSet and Route URLs

After the serializers are created we need to create a view to the API and connect it to the Django URLs. So we will add 2 viewsets for each of the models we created in product_api/views.py

After the viewsets has been defined, then create a new file product_api/urls.py and setup the router configuration. This is done to make it easier for us to manage our routes in the Django. This product_api/urls.py will be used to hold all urls related to product_api app.

Then finally let’s connect the main Django URL at my_rest_api/urls.py to point to the app’s URL file that we have created.

5. Testing API with HTTP method

And now we ready to test our REST API. don’t forget to running your django server with runserver command. If we go to the http://127.0.0.1:8000/api URL now, we should be able to see the browsable api.

In Django REST Framework basically you can test your API directly on this webpage. for example is like this

But in this example I will use the Third Party tool named Insomnia. If you not familiar with this tool, you can also use another tools like Postman. So let’s start with HTTP method for REST API.

  • OPTIONS → use this toto get supported operations on resources from the REST server.
Options operation on category product
  • POST → use this to input data to server
input data to Category
input data to Item with “food” as category
  • PUT → use this to update data on the REST server
  • GET → use this to get data from REST server
Get all data from product item
Add id on url to get a specific data
  • DELETE → use this to delete data from the REST server

After deleting let’s get the item :

The item successfully deleted from REST server.

And that’s it, you can see how easy it is to configure Django Rest Framework and start building REST APIs. We brought up a fully functional API with very little code.

Of course this is not suitable for use in the REST API for production. We haven’t set up authentication for our REST API to differentiate the use of private and public APIs. Also we haven’t set the response message to the API when it’s actually used. For advanced REST API settings, I will probably explain in the next article.

Complete Source Code

Closing remarks

Thank you for following this tutorial to the end. Hopefully this article can help you, see you in the next article.

--

--

Andika Pratama

Fresh Graduate of Computer Science at Universitas Syiah Kuala, Software Engineer. Check my github on github.com/Andika7