Consuming API with Django and Chart.js [Part 1]
Tags: python, django, javascript, webdev
Published: 2021-09-27 08:23:15

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](https://api.coindesk.com/v1/bpi/historical/close.json?start=2021-08-08&end=2021-08-17&index=[USD]) 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](https://www.python.org/downloads/). 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 a few steps to go 😀 and then we'll proceed to code.
![relax](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g5mduiyzx9ug1ymd5tg5.gif)

### 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.
```javascript
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 the 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 the HTML templates
```javascript
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.
```javascript
STATIC_URL = '/static/'
STATICFILES_DIRS = [
    BASE_DIR/ 'static'
]

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

We won't 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 won't be needing the 'models.py' file😅. Trust me on this one😁. At the moment, your folder structure should be looking like this 👇
![folder structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipez7s7l8kigr1fd2jc3.png)

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 it in any browser of your choice. You should be able to see something similar to this 👇
![Django default page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i70ngak6274xhrpkvhcm.png)
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 named “templates”. Create a base.html file in it. Then paste the following code in the html file.
```javascript
<!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👇.
```javascript
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.
```javascript
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.py
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.
```javascript
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 on your server. You should see the h1 content in our base.html file on the page.
![Default page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x3ernymv1kkidqpqd40.png)

(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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uolhpii5ogbppohj5dgw.png)

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](https://dev.to/faruqt/consuming-coindesk-s-api-with-django-and-chart-js-part-2-me5) ![May the force be with you](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fga4eh4ksxapp0gvpwk2.gif)

If you have any questions, feel free to drop them as a comment or send me a message on [Linkedin](https://www.linkedin.com/in/faruq-abdulsalam) or [Twitter](https://twitter.com/Ace_II) and I'll ensure I respond as quickly as I can. Ciao 👋