How to consume RESTful APIs with Django - the easiest way
Tags: django, restful, api, json
Published: 2020-04-29 21:35:13

---
title: "How to consume RESTful APIs with Django - the easiest way"
published: true
description: "How to consume RESTful APIs with Django - the easiest way"
tags: django, restful, api, json
cover_image: https://images.unsplash.com/photo-1556889487-b6f8d3fc728b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=853&q=80
---

Originally posted on [my blog](https://rapidpython.com/how-to-consume-restful-apis-with-django-the-easiest-way/)

## Introduction

> A REST API defines a set of functions which developers can perform requests and receive responses via HTTP protocol such as GET, POST, PUT and DELETE

Think REST API as a web service that provides you the data you want to use in your application(mobile or front-end client).

The key components for a REST API request are:

**GET** — The most common option, returns some data from the API based on the given endpoint.
**POST** — Creates a new record and add it to the database.
**PUT** — Update an existing record.
**DELETE** — Deletes the record on the given endpoint.

In this guide, we will use [JSONPlaceholder](https://jsonplaceholder.typicode.com/) API.

The final project [Here](https://github.com/xarala221/consume-restfull-api-with-django.git)

## Setting up

Create a new virtual environment

```shell
mkdir use_rest_api_with_django && cd use_rest_api_with_django
virtualenv venv
```

Activate our virtual environment

```shell
source /ven/bin/activate
```

Install Django and requests Library

```shell
pip install Django requests
```

Create a new Django project from the terminal

```shell
django-admin startproject consume_restful_api .
```

Don't forget to put the dot(.) at the end.

Create a simple **Django** application

```shell
python manage.py startapp main_app
```

Register our newly created app

```python
# settings.py
INSTALLED_APPS = [
   'django.contrib.admin',
   'django.contrib.auth',
   'django.contrib.contenttypes',
   'django.contrib.sessions',
   'django.contrib.messages',
   'django.contrib.staticfiles',
   'main_app.apps.MainAppConfig' # add this
]
```

Change the templates directory

```python
# settings.py
TEMPLATES = [
   {
       'BACKEND': 'django.template.backends.django.DjangoTemplates',
       'DIRS': [os.path.join(BASE_DIR, 'templates')],  # add this
       'APP_DIRS': True,
       'OPTIONS': {
           'context_processors': [
               'django.template.context_processors.debug',
               'django.template.context_processors.request',
               'django.contrib.auth.context_processors.auth',
               'django.contrib.messages.context_processors.messages',
           ],
       },
   },
]
```

Inside the **views.py** file add this

```python
# views.py
import requests
from django.shortcuts import render


def home(request):
   # get the list of todos
   response = requests.get('https://jsonplaceholder.typicode.com/todos/')
   # transfor the response to json objects
   todos = response.json()
   return render(request, "main_app/home.html", {"todos": todos})
```

Create the required templates

```shell
mkdir templates && mkdir templates/main_app
touch templates/base.html && touch templates/main_app/home.html
```

base.html

```html
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>How to consume RESTful APIs with Django</title>
  </head>
  <body>
    <h2>How to consume RESTful APIs with Django</h2>

    {% block content %} {% endblock content %}
  </body>
</html>
```

home.html

```html
<!-- base.html -->
{% extends "base.html" %} {% block content %}
<ul>
  {% for todo in todos %}
  <li>{{ todo.id }} - {{ todo.title }}</li>
  {% endfor %}
</ul>
{% endblock content %}
```

Let's add some styling with **bootstrap**

Change the base.html file

```html
<!-- base.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
      integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
      crossorigin="anonymous"
    />
    <title>How to consume RESTful APIs with Django</title>
  </head>
  <body>
    <h2 class="text-center">How to consume RESTful APIs with Django</h2>

    <div class="container">
      {% block content %} {% endblock content %}
    </div>
  </body>
</html>
```

And home.html

```html
<!-- home.html -->
{% extends "base.html" %}

{% block content %}
<div class="col-md-6 col-auto">
  <div class="card">
    <div class="card-header">
      Todos
    </div>
    <ul class="list-group list-group-flush">
      {% for todo in data %}
      <li class="list-group-item">{{ todo.id }} - {{ todo.title }}</li>
      {% endfor %}
    </ul>
  </div>
</div>
{% endblock content %}
```

## Conclusion

In this article, we've learned how to consume RESTful APIs with Django and Python **requests** Library.

Thanks for reading.