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 https://jsonplaceholder.typicode.com/users.

Prerequisite

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 YOUR-VIRTUAL-ENV-NAME

virtualenv consume-api-in-django-venv

Activate your virtual environment

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

YOUR-VIRTUAL-ENV-NAME\Scripts\activate

consume-api-in-django-venv\Scripts\activate

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/ manage.py bookapp/ init.py settings.py urls.py asgi.py wsgi.py

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. manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin and manage.py.

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/__init__.py: 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.py: Settings/configuration for this Django project. Django settings will tell you all about how settings work.

6. bookapp/urls.py: 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/asgi.py: An entry-point for ASGI-compatible web servers to serve your project. See How to deploy with ASGI for more details.

8. bookapp/wsgi.py: 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 manage.py runserver

you can see in command prompt like below:

We can see deleveloper server started at http://127.0.0.1:8000/. Open url http://127.0.0.1:8000/ 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 manage.py makemigrations

python manage.py migrate

Create a superuser

python manage.py createsuperuser

Run the application and check admin panel

python manage.py runserver

Development server is running, check url in browser:

http://127.0.0.1:8000/

http://127.0.0.1:8000/admin/

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 manage.py and type this command:

python manage.py startapp YOUR-DJANGO-APP-NAME

python manage.py 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/ init.py admin.py apps.py migrations/ init.py models.py tests.py views.py

Make your newly created app entry in Django settings file

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

Save and close the file.

Rest rest api data

We are using this rest api url https://jsonplaceholder.typicode.com/users. 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/views.py

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('https://jsonplaceholder.typicode.com/users')

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

return HttpResponse("Users")
pass

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

We have to create a new urls.py file inside your django app. After creating urls.py, 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 urls.py file

Open consume-api-in-django/bookapp/bookapp/urls.py file

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

Run the application

python manage.py runserver

Check in browser http://127.0.0.1:8000/. 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 settings.py file of django project

Open consume-api-in-django/bookapp/bookapp/settings.py 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

Users

Change HTTPResponse to html template in views

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

Refresh the url in browser http://127.0.0.1:8000/

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

Let us pass data in views.py to users.html

Open consume-api-in-django/bookapp/myapp/views.py 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('https://jsonplaceholder.typicode.com/users')

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

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

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

<!doctype html>

Consume Rest Api

Users

{% for user in users %} {% endfor %}
Id Name Username Email Phone
{{ user.id }} {{ user.name }} {{ user.username }} {{ user.email }} {{ user.phone }}

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

TensorFlow

  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

PySpark

  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

PyTorch

  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