In this blog, we will consume rest api in django web application. Rest api url is https://jsonplaceholder.typicode.com/users.
1) Python should be installed in your system
2) pip installation
3) Install virtual environment
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
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
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".
Make sure your virtual environment should be activated. Then install django module.
pip install django
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.
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:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py 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.
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
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.
We are using this rest api url https://jsonplaceholder.typicode.com/users. This rest api we are going to consume in django application.
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
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.
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
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'), ]
Open consume-api-in-django/bookapp/bookapp/urls.py file
path('', include('myapp.urls')),
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.
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 consume-api-in-django/bookapp/myapp directory.
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>
Users
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:
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
<!doctype html>
Users
Id | Name | Username | Phone | |
---|---|---|---|---|
{{ user.id }} | {{ user.name }} | {{ user.username }} | {{ user.email }} | {{ user.phone }} |
We have successfully consumed rest api and displayed in webpage.