logo

Get in touch

Awesome Image Awesome Image

Python Development December 6, 2021

Easy Step-by-Step Guide to Develop REST APIs with Django REST Framework

Written by Dharmesh Patel

30,243

Django framework has become one of the preferred frameworks of developers. It’s quite obvious as it handles data serialization and works seamlessly with Django’s ORM. That’s why Django is a powerful and flexible toolkit for building web APIs, including REST API.

REST API has become a standardized method to provide data to other applications. These applications further process the data and use it for various purposes. That’s why REST API is of critical importance and Django is a perfect platform to create one. In this blog post, we’re going to go through straightforward steps to develop REST APIs with Django Rest Framework (DRF). Let’s get started!

Steps Involved in Creating REST API with Django Framework

The process of creating REST APIs in the Django framework can be divided into five easy steps. It starts with setting up Django and finishes with creating URI endpoints. Here are they:

  1. Install Django & set up a new project
  2. Create a model in the database for Django ORM 
  3. Set up the Django REST Framework
  4. Serialize the models
  5. Create the URI endpoints to view the serialized data

Seems simple enough, doesn’t it? Let’s get started then!

Step 1: Install Django Framework

The first obvious and easiest step involved in this process is installing the Django framework. We’d suggest you create a new virtual environment for your project as it allows you to manage dependencies separately.

We’re going to use pyenv, a simple Python management tool, to create a virtual environment. It’s quite a convenient tool as it allows you to change global Python versions, install multiple Python versions, set project-specific Python versions, and manage virtual Python environments.

1. Install Pyenv

$ git clone https://github.com/pyenv/pyenv.git ~/.pyenv

2. Define Environment Variable

Now we need to define the environment variable PYENV_ROOT to point to the path where pyenv repo is cloned. Then, add $PYENV_ROOT/bin to the $PATH for access to the pyenv command-line utility.

$ pyenv virtualenv django-rest
Looking in links: /tmp/tmpjizkdypn
Requirement already satisfied: setuptools in
/home/bennett/.pyenv/versions/3.6.8/envs/django-rest/lib/python3.6/site-packages (40.6.2)
Requirement already satisfied: pip in
/home/bennett/.pyenv/versions/3.6.8/envs/django-rest/lib/python3.6/site-packages (18.1)
$ pyenv local django-rest

3. Add Pyenv Unit to Shell & Restart the Shell

$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bashrc

Apply the following command to restart the shell:

$ exec "$SHELL" 

4. Install Python & Create a Virtual Environment
Apply the below command to install the latest python version. Please note that 3.10.0 is the latest version as of the date we’re writing this article. Thus you will need to install the one latest whenever you are trying to install.

$ pyenv install 3.10.0

To create an environment for the project:

$ pyenv virtualenv 3.7.4 blog

5. Create a Django Project

Now, apply the below command to create a project:

$ django-admin startproject mysite

To verify the project creation, go to the directory and you will find a new folder there:

$ ls
mysite/

Now go inside the folder to find everything you need to run a site:

$ cd mysite/
$ ls
manage.py* mysite/

6. Test Run Django Server

Use the below command to see if it works or not:

$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
You have 17 unapplied migrations. The project may not work properly until you apply the migrations
for apps: admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
May 17, 2019 - 16:09:28
Django version 2.2.1, using settings 'mysite.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

You can go to the localhost:8000 and see the Django welcome screen. Easy first step, wasn’t it?

7. Create API App

For the ease of use and management, we will separate the Django project into separate apps. Here’s how you can create a new API app:

$ python manage.py startapp myapi
$ ls
db.sqlite3 manage.py* myapi/ mysite/

As you can see, we’ve named it ‘myapi.’

8. Connect API App with Django and Register the Project

Now that we’ve created an API app, we now need to connect Django to it and register with the project we just created.
To do so, we first need to edit the mysite/settings.py and apply the following:

INSTALLED_APPS = [
'myapi.apps.MyapiConfig',
... # Leave all the other INSTALLED_APPS
]

9. Migrate Models to the database

Once we create or make changes to a model, we need to tell Django to migrate those changes to the database. Moreover, Django has its own built-in models, and thereby we need to migrate them to our database.
If you’re wondering that we forgot to create a database, then don’t worry. Django creates SQLite databases on its own, and it’s more than good enough.
Apply the following to migrate the models:

$ python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying sessions.0001_initial... OK

Step 2: Create a model in the database for Django ORM

Now that we’re done with setting up Django and the project, the next step is to create a model in the database. We will do it in the myapi/models.py file.

1. Add Person and Species

from django.db import models
class Species(models.Model):
name = models.CharField(max_length=100)
classification = models.CharField(max_length=100)
language = models.CharField(max_length=100)
class Person(models.Model):
name = models.CharField(max_length=100)
birth_year = models.CharField(max_length=10)
eye_color = models.CharField(max_length=10)
species = models.ForeignKey(Species, on_delete=models.DO_NOTHING)

2. Run the Migrations

To create new migration files:

(drf) $ python3 manage.py makemigrations
Migrations for 'myapi':
myapi/migrations/0001_initial.py
- Create model Species
- Create model Person

Now, run the migration command:

(drf) $ python3 manage.py migrate 
Operations to perform:
Apply all migrations: myapi
Running migrations:
Applying myapi.0001_initial... OK

Step 3: Set up Django REST Framework

Before we serialize the data from the database, we need to install the Django REST framework. Here’s how you can do it:

$ pip install djangorestframework

Now, we just connect Django with the installation:

INSTALLED_APPS = [
# All your installed apps stay the same
...
'rest_framework',
]

Also Read: Django vs. Flask: A Comparative Guide for Making the Right Business Decision

Step 4: Serialize the Models

After adding models and installing the REST framework, the next important step is to set up the DRF serializers. It will turn the Personal model and species into JSON, which the API can employ to transfer the data back to the user.
To serialize the models, we need to create a new file myapi/serializers.py.

from rest_framework import serializers
from myapi.models import Person, Species
class PersonSerializer(serializers.ModelSerializer):
class Meta:
model = Person
fields = ('name', 'birth_year', 'eye_color', 'species')
class SpeciesSerializer(serializers.ModelSerializer):
class Meta:
model = Species
fields = ('name', 'classification', 'language')

Step 5: Create API URLs

The 5th and final step is to create a view to the API and connect to the Django URLs. For that, we need to add two viewsets of each model we created. Here’s how you can do it:

from rest_framework import viewsets
from myapi.serializers import PersonSerializer, SpeciesSerializer
from myapi.models import Person, Species
class PersonViewSet(viewsets.ModelViewSet):
queryset = Person.objects.all()
serializer_class = PersonSerializer
class SpeciesViewSet(viewsets.ModelViewSet):
queryset = Species.objects.all()
serializer_class = SpeciesSerializer

Now that we’ve created the viewsets, we now need to route the API endpoint to a viewset. For that, first create a new file myapi/urls.py and add the router configuration as shown below.

from django.urls import include, path
from rest_framework import routers
from myapi.views import PersonViewSet, SpeciesViewSet
router = routers.DefaultRouter()
router.register(r'people', PersonViewSet)
router.register(r'species', SpeciesViewSet)

urlpatterns = [
path(”, include(router.urls)),
]

As the final step of the procedure, let’s connect the major URL of mysite project to the URL of the app.

from django.urls import path, include
urlpatterns = [
path('test-project/', include('myapi.urls')),
]

All done? Now the URL encompasses all the API methods (GET, POST and PUT). Now it’s time to test the API and see how it works!

Step 6: Test the API

Next, go to the Test project species API, and you will be able to use the API where you can add species. You can add the species and see if you get 201 success messages in return.

Et voila! You have successfully deployed the REST API using Django Framework. Now you see why many prefer Django development company, don’t you? It’s fast and doesn’t make a lot of fuss.

Inexture Solutions: Next Gen Django Development Company

Many people ask us why we prefer Django so much when most of the developers are preferring other frameworks. We have a simple answer to that, and it’s that we like to stay a step ahead. We, at Inexture, not only like to keep pace with the latest happenings but also peek into the future to use the best technologies.

We pride ourselves in our Django developers and Python development services we offer. We’ve got a stellar portfolio and would love to be a part of your next endeavour. Let’s get in touch!

Bringing Software Development Expertise to Every
Corner of the World

United States

India

Germany

United Kingdom

Canada

Singapore

Australia

New Zealand

Dubai

Qatar

Kuwait

Finland

Brazil

Netherlands

Ireland

Japan

Kenya

South Africa