Consuming API  with Django and Chart.js [Part 1]

Consuming API with Django and Chart.js [Part 1]

This is going to be a 3-part series tutorial, you are going to learn how to consume an API in Django and present it in graphical format using Chart.js. We will be making use of CoinDesk’s Api “Historical BPI Data of bitcoin”. Here is a sample of an API we'll be making use of.

PART 1

Setup

If you already know how to do this, you can skim through part 1 then move to the next part of the series.

I’ll assume that you already have python installed on your machine. If you don't, you can download and set it up via this link. Please ensure you download the latest version of python. (Python 3.97)

Open the Command Line on Windows, Terminal on Mac and Linux and navigate to the directory where you want to store the project and create a new directory

mkdir bitcoin_api

Move into the new directory

cd bitcoin_api

Create a Virtual environment.

It is recommended to always create a virtual environment before you start your project. This helps you to separate the packages you use in this application from other applications; any change you make here wont affect the same package in another application on your system. To create a Virtual environment on your system; run this command:

For mac/unix users: python3 -m venv env
For windows users: py -m venv env

After creating the environment, activate it by running :

For mac/unix users: source env/bin/activate
For windows users: .\env\Scripts\activate

You can deactivate it by simply running the command below, but you don't have to deactivate it yet.

deactivate

Installing Django

Now let us proceed to installing Django,

pip install django

We are officially done with setting up our system for the django project 🤝, now let us proceed to the project setup itself.

You thought we were done, aye? 😅. Don't worry we have just few steps to go 😀 and then we'll proceed to coding. relax

Setting up the project

Create a new django project and name it “bitcoin-price”

django-admin startproject bitcoin_price

Move into the project folder

cd bitcoin_price

Create a new application named “price”

python manage.py startapp price

Next we have to add the name of the newly created app to the settings.py file in our project directory “bitcoin-price”. Open the settings.py file; under the “installed apps” setting add the string “price” to it so it ends up looking like this.

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    #my_app
    'price',
]

Next we’ll add our html template and also static files paths to the settings which will handle our html, css and javascript files. We will only be changing the content of 'DIRS' here. All we are doing is declaring the path to the folder where we will store our own html templates

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR/ 'templates'],
        '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',
            ],
        },
    },
]

At the bottom of our settings file you'll see the static files section. Add this under the STATIC_URL configuration

STATICFILES_DIRS = [
    BASE_DIR/ 'static'
]

Your static file configuration should now look like this.

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR/ 'static'
]

That’s all we need to do under the settings.py file.

We wont be needing a database for this tutorial as the API data will be fetched and rendered in real-time. So you can go ahead and delete the models.py file under your app “price”. Yes you read that right, we wont be needing the models.py file😅. Trust me on this one😁. At the moment, your folder structure should be looking like this 👇 folder structure

Now migrate your “changes” with this command

python manage.py migrate

Then you can start your server to ensure that everything is working properly

python manage.py runserver

Copy this url: http://127.0.0.1:8000 and open in any browser of your choice. You should be able to see something similar to this 👇 Django default page Next we’ll be creating the static and template folders. ENSURE you are in the folder that contains the manage.py file

Create the static folder and in it, two extra folders named css and js respectively. They’ll hold our javascript and styling codes later on.

Then create a folder name “templates”. Create a base.html file in it. Then paste the following code in the html file.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>Bitcoin Price Chart</title>
  </head>
  <body>

    <h1> CoinDesk's Bitcoin Api Data </h1>

  </body>
</html>

Now we need to configure our url so we can view our html page. Open urls.py file in the bitcoin_price folder. We need to import the include function and link the url to our "price" application. We will set it up like this👇.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include("price.urls"))
]

It is similar to what we have, but we just need to edit line 2 and add line 5. Next we open the price folder and create a new file with the name urls.py. Copy this into the new file.

from django.urls import path
from .views import chart

urlpatterns = [
    path("", chart, name="chart"),
]

We'll be creating the chart function we are importing into our url shortly. Sorry for bringing it in before creating it.

Views

Here is where we'll place the heart of our project. For now, we'll just add a small function, so we can confirm that we can view our html files properly. Here is the code we'll be adding to our views.py file.

def chart(request):
     context = {}
     return render(request, 'base.html', context)

When we try to access our url from the browser, the chart function gets called and it renders our base page. Ignore the context dictionary for now. It is for future use😉.

You might see this error in your command line or terminal : "ModuleNotFoundError: No module named price.urls .This is because our server was still running when we made the changes so it cannot read the urls.py file we just created. Shut down the server with

 'Control + C' buttons on your keyboard

and restart the server to ensure that everything is working properly

python manage.py runserver

Refresh the page you opened in your server. You should see the h1 content in our base.html file on the page. Default page

(If you are not seeing anything. Two things might have happened:

  1. You closed the page. Open this url: 127.0.0.1:8000 in your browser
  2. You already took down the server. Run the command below.
    python manage.py runserver
    then open this url 127.0.0.1:8000 in your browser.
    
    You should now be able to see the page above👆.

Finally we create a template folder in our price directory and add a chart.html file to it.

Voilà!!! We have successfully finished setting up our Django project. Your project file structure should look like this now. New FolderStructure

Now let’s get started with writing the logic codes ✍️. No, we won't be doing that in Part 1 😅. Let's get some rest and push the major work to the next part of the series. If you are the strong one 💪, you can proceed straight away to Part 2 May the force be with you

If you have any question, feel free to drop it as a comment or send me a message on Linkedin or Twitter