Web development with python- Django (part-6)

We have learned some basics of django so far which is very fundamental.
Now let’s see somthing more.
When we develop any website ,it is very common that we use REST api.
Normally we get some json data from REST call and then after parsing the data we display to our template. This scenario is very common and necessary for any web developer .
Today we will see how to do that task.

Requests is the HTTP library for Python which  allows you to send organic, grass-fed HTTP/1.1 requests, without the need for manual labor. There’s no need to manually add query strings to your URLs, or to form-encode your POST data. Keep-alive and HTTP connection pooling are 100% automatic.
Requests is one of the most downloaded Python packages of all time, pulling in over 400,000 downloads each day.

So to use REST api we will use requests  library.
Lets install it to our machine.

pip install requests


As we are making a personal blog site hence we will use such a API which will return some demo blog ID,title and description.
This API will serve our purpose perfectly and have a look the output json response.


Our target is to call a REST API, which is  in this case https://jsonplaceholder.typicode.com/posts, and then get json response(contains blog IDs, titles and descriptions) . Finally show the data(blog ID, title, description) into our template like below.


Goto  mysite>personal>view.py
Write these simple code:

from django.shortcuts import render
import requests

def index(request):
resp = requests.get(‘https://jsonplaceholder.typicode.com/posts’)
return render(request, ‘personal/home.html’,{
‘data’: data

Capture.PNGHere at line number two, we’ve just imported request library to use.
At line number 5,6 we have called the API and then got the data as json format.
As we will use this data in the home.html template that’s why at line number 8 we have passed our data to template.

Now goto mysite\personal\templates\personal\home.html
and rewrite completely home.html like below.



As our data is an arrayList of objects so we have to loop through each object to show all data.
Here we will show all blog ID,title,description using a for loop.

Finally if we run this we will get our desired output.


For this moment that’s all .
Hope we will come back again till then stay good.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s