How to Fetch API Data in Django Template?

Published On: 15/12/2022 | Category: Django

Hi Dev,

Here, I will show you how to works how to display api data in django template. it's simple example of how to get data from external api in django template. this example will help you how to display json data in django template. step by step explain django display api data in django template. Let's get started with django display api data in django template example.

One of the most popular applications of the Django Rest Framework is the display of API data in Django templates. You might need to use API data at some point in your projects. In this blog, we are going to learn How to display API response in HTML using Django Template.

Here i will give you we will help you to give example of django search autocomplete input field example. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
cd example
django-admin startapp blog
Step 3: Install required library

Install requirements The httprequest standard is extended by the request rest framework, which offers flexible request parsing that enables users to handle requests containing JSON data or other media types in the same way that they would typically handle form input.

pip install requests

Step 4: Update

Next, you need to add it in the file as follows:


Step 5: Creating the Views

In this step, we need to create the views for performing fetch data from jsonplaceholder post api record.Open the blog/ file and add:

from django.shortcuts import render
import requests

# Create your views here.
def index(request):
    return render(request,'api.html',{'response':response})

Step 6: Creating Templates

Next, open the blog/templates/api.html file and the add:

    <title>API Display</title>
    <h1>List of posts</h1>
    {% for i in response %}
    <strong>{{}} - {{i.title}} ,</strong><br>
    {% endfor %}

Step 7: Creating Urls

In this section, we’ll create the urls to access our views.Go to the blog/ file and update it as follows:

from django.urls import path
from blog import views

urlpatterns = [
    path('', views.index, name='index'),

Next, we will require the modify the your root preoject folder lets update the file.

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('blog.urls')),

Step 8: Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver

Next, go to the http://localhost:8000 address with a web browser.

I Hope It will help you....