Consume Rest API in Django Web Application

Consume Rest API in Django Web Application

In this blog, we will consume rest api in django web application. Rest api url is


1) Python should be installed in your system

2) pip installation

3) Install virtual environment

Create a new virtual environment

Go to your project directory and create a directory for a new django project

I am creating a directory called consume-api-in-django for django project. You can choose name according to your choice. Open command prompt and go to project folder.

F: cd F:\python-projects\django-projects

mkdir consume-api-in-django

cd consume-api-in-django

Create a virtual environment

In this example, i am keeping my virtual environment name is consume-api-in-django-venv. You can keep name according to your choice.


virtualenv consume-api-in-django-venv

Activate your virtual environment

I am using windows system, so need to activate like below:



We can see on the left side virtual environment name is showing in the bracket. That means virtual environment is activated.

If you want to deactivate your virtual environment. you can type "deactivate".

Install django in activated virtual environment

Make sure your virtual environment should be activated. Then install django module.

pip install django

Create a django project in activated environment

django-admin startproject YOUR-DJANGO-APPLICATION-NAME

django-admin startproject bookapp

I have used bookapp as django project name. You can keep name according your choice.

When we create django project, django will auto-generate some code that establishes a Django project – a collection of settings for an instance of Django, including database configuration, Django-specific options and application-specific settings.We can see folder name is created with name of django project.

Let us see what startproject created:

bookapp/ bookapp/

These files are:

1. The outer bookapp/ root directory is a container for your project. Its name doesn’t matter to Django; you can rename it to anything you like.

2. A command-line utility that lets you interact with this Django project in various ways. You can read all the details about in django-admin and

3. The inner bookapp/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it (e.g. mysite.urls).

4. bookapp/ An empty file that tells Python that this directory should be considered a Python package. If you’re a Python beginner, read more about packages in the official Python docs.

5. bookapp/ Settings/configuration for this Django project. Django settings will tell you all about how settings work.

6. bookapp/ The URL declarations for this Django project; a “table of contents” of your Django-powered site. You can read more about URLs in URL dispatcher.

7. bookapp/ An entry-point for ASGI-compatible web servers to serve your project. See How to deploy with ASGI for more details.

8. bookapp/ An entry-point for WSGI-compatible web servers to serve your project. See How to deploy with WSGI for more details.

Run the application

cd bookapp

python runserver

you can see in command prompt like below:

We can see deleveloper server started at Open url in browser.

You should get django default page like below:

Run makemigrations and migrate command

makemigrations is responsible for creating new migrations based on the changes you have made to your models and migrate executes those SQL commands in the database file. Stop the python webserver by pressing ctrl + c and run following commands:

python makemigrations

python migrate

Create a superuser

python createsuperuser

Run the application and check admin panel

python runserver

Development server is running, check url in browser:

You have to enter username and password details which we created from command prompt, then click on Log in. After successful login, you will get screen like below:

Stop the development server and create a django app.

Create a django App

To create your app, make sure you’re in the same directory as and type this command:

python startapp YOUR-DJANGO-APP-NAME

python startapp myapp

Here my django app name is myapp. You can keep name according to your requirement.

That’ll create a directory myapp, which is laid out like this:

myapp/ migrations/

Make your newly created app entry in Django settings file

Open consume-api-in-django/bookapp/bookapp/ file. Add 'myapp' in INSTALLED_APPS list in file.

Save and close the file.

Rest rest api data

We are using this rest api url This rest api we are going to consume in django application.

Install requests module in activated virtual environment

Requests is an elegant and simple HTTP library for Python. Requests allows you to send HTTP/1.1 requests extremely easily. To install Requests, simply run this simple command in your terminal of choice:

pip install requests

How to use Request module?

Making a request with Requests is very simple. Begin by importing the Requests module:

import requests

r = requests.get('YOUR-WEB-PAGE-URL')

Now, we have a Response object called r. We can get all the information we need from this object.

Consume rest api in django application

Create a new function in consume-api-in-django/bookapp/myapp/

from django.shortcuts import render from django.http import HttpResponse import requests

Create your views here.

def users(request):

#pull data from third party rest api
response = requests.get('')

#convert reponse data into json
users = response.json()

return HttpResponse("Users")

Create a new file called inside this consume-api-in-django/bookapp/myapp folder

We have to create a new file inside your django app. After creating, you have to write following line of code.

from django.urls import path

from . import views

urlpatterns = [ path('', views.users, name = 'users'), ]

Add newly created urls file in main django file

Open consume-api-in-django/bookapp/bookapp/ file

path('', include('myapp.urls')),

Run the application

python runserver

Check in browser You should get page like below:

You should see users data in terminal or command prompt like below:

We are able to fetch data from third party website. Now we have to display in webpage.

Display data in html template

Modify file of django project

Open consume-api-in-django/bookapp/bookapp/ file. Add templates directory in TEMPLATES list.

import os

'DIRS': [os.path.join(BASE_DIR, 'templates')],

Create a templates directory inside your django application

Create a templates directory inside consume-api-in-django/bookapp/myapp directory.

Create a users.html file inside consume-api-in-django/bookapp/myapp/templates/

Create a users.html file and write following lines of code. We are using Bootstrap in html, so that page should be responsive, mobile-first sites. If you don't want you can remove bootstrap.

<!doctype html>

Consume Rest Api


Change HTTPResponse to html template in views

Open consume-api-in-django/bookapp/myapp/ file and change like below.

Refresh the url in browser

Start your application, if it not running. You will webpage like below:

Let us pass data in to users.html

Open consume-api-in-django/bookapp/myapp/ file and modify users function. We need to pass users data to users.html file.

from django.shortcuts import render from django.http import HttpResponse import requests

Create your views here.

def users(request):

#pull data from third party rest api
response = requests.get('')

#convert reponse data into json
users = response.json()

return render(request, "users.html", {'users': users})

Modify consume-api-in-django/bookapp/myapp/templates/users.html file

<!doctype html>

Consume Rest Api


{% for user in users %} {% endfor %}
Id Name Username Email Phone
{{ }} {{ }} {{ user.username }} {{ }} {{ }}

Refresh the browser, you should get webpage like below:

We have successfully consumed rest api and displayed in webpage.

In [ ]:

Machine Learning

  1. Deal Banking Marketing Campaign Dataset With Machine Learning


  1. Difference Between Scalar, Vector, Matrix and Tensor
  2. TensorFlow Deep Learning Model With IRIS Dataset
  3. Sequence to Sequence Learning With Neural Networks To Perform Number Addition
  4. Image Classification Model MobileNet V2 from TensorFlow Hub
  5. Step by Step Intent Recognition With BERT
  6. Sentiment Analysis for Hotel Reviews With NLTK and Keras
  7. Simple Sequence Prediction With LSTM
  8. Image Classification With ResNet50 Model
  9. Predict Amazon Inc Stock Price with Machine Learning
  10. Predict Diabetes With Machine Learning Algorithms
  11. TensorFlow Build Custom Convolutional Neural Network With MNIST Dataset
  12. Deal Banking Marketing Campaign Dataset With Machine Learning


  1. How to Parallelize and Distribute Collection in PySpark
  2. Role of StringIndexer and Pipelines in PySpark ML Feature - Part 1
  3. Role of OneHotEncoder and Pipelines in PySpark ML Feature - Part 2
  4. Feature Transformer VectorAssembler in PySpark ML Feature - Part 3
  5. Logistic Regression in PySpark (ML Feature) with Breast Cancer Data Set


  1. Build the Neural Network with PyTorch
  2. Image Classification with PyTorch
  3. Twitter Sentiment Classification In PyTorch
  4. Training an Image Classifier in Pytorch

Natural Language Processing

  1. Spelling Correction Of The Text Data In Natural Language Processing
  2. Handling Text For Machine Learning
  3. Extracting Text From PDF File in Python Using PyPDF2
  4. How to Collect Data Using Twitter API V2 For Natural Language Processing
  5. Converting Text to Features in Natural Language Processing
  6. Extract A Noun Phrase For A Sentence In Natural Language Processing