1000 Python Questions
Get 1 Python question daily. Join this telegram channel https://t.me/python1000questions
Advertise with us
api requests   2   3211
Get latest Bitcoin and other crypto-currencies rates using python Django

Everybody is investing in bitcoins. 

James Howells is trying to dig a landfill site to get 7500 bitcoins that were dumped there in 2013.

To be a good investor, it is necessary that you keep track of ups and downs in the market. '

There are multiple platforms where you can track the price of bitcoin. But for a python programmer that is no fun. Being a python programmer we will develop our own project where we can get latest bitcoin and other crypto-currency prices.

Let's start.

Virtual environment setup:

It is always recommended to use virtual environment for all your python and Django projects.

Create a virtual environment using python3 using below command.

virtualenv -p /usr/bin/python3 crypto

Now activate the virtual environment.

source crypto/bin/activate

Install the latest Django version and other required libraries.

For now only requests package is required. We will add other packages later if required.

pip install django requests

This will install Django 2.0 and requests package along with some other package.

You can verify the same by running command pip freeze .

(crypto) rana@Brahma: crypto$ pip freeze

Creating new Django Project:

Once virtual environment has been setup and activated, create a new django project.

django-admin startproject crypto

Go to crypto project directory and list the files.

get latest bitcoin and other crypto currencies rates using python django

Since we are working on Django 2.0 , we need to take care of few things which we will highlight as we progress.

Now create a new app 'bitcoin'.

python manage.py startapp bitcoin

Add this app to the list of installed apps in settings.py  file.

Project Setup:


Create urls.py  file in new app bitcoin.

from django.urls import path
from . import views

app_name = 'bitcoin'

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

Django 2.0 Note: Adding app_name  in urls.py  is require now, otherwise you will get the below error.

'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

Include urls of bitcoin app in project's urls.py  file.  


Create a directory templates/bitcoin  in bitcoin app.

Inside this directory create a new html file, index.html . You can leave this file empty as of now or to make sure things are working fine, put some text there.  


Create a new function index in views.py  file.

For now this function will only render the index.html  created in previous step.

We will add more functionality in coming steps.

from django.shortcuts import render

def index(request):
    data = {}
    return render(request, "bitcoin/index.html", data)

Verifying basic setup:

Once above steps are completed, run the django server.

$python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

December 28, 2017 - 09:00:43
Django version 2.0, using settings 'crypto.settings'
Starting development server at
Quit the server with CONTROL-C.

Go to localhost:8000  and you can see the text which you putted in index.html  file.  

Getting bitcoin prices:

We will use the coinmarktecap api to fetch the latest data.

In views.py  file add a new function to get bitcoin data. This function will call the api url and get the currency data. Data returned is Json string. Convert it to Json Object.

# return the data received from api as json object
def get_crypto_data():
    api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=10"

        data = requests.get(api_url).json()
    except Exception as e:
        data = dict()

    return data

Make a call to get_crypto_data  in index function and return the rendered response.

Complete views.py  file :

from django.shortcuts import render
import requests

def index(request):
    data = {}
    data["crypto_data"] = get_crypto_data()
    return render(request, "bitcoin/index.html", data)

# return the data received from api as json object
def get_crypto_data():
    api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=10"

        data = requests.get(api_url).json()
    except Exception as e:
        data = dict()

    return data

Rendering Data in Template:

Render the coins data row wise using a for loop in template as shown in html code below.

        <title>Latest Bitcoin Price - ThePythonDjango.Com</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
    <body style="margin:20px;">
        <div class="alert alert-dark" role="alert">
            <span style="font-size:30px;">Bitcoin Latest Price</span> <span style="font-size:15px;">by <a href="http://ThePythonDjango.Com" target="_blank">ThePythonDjango.Com</a></span>
        <div class="list-group">
            <div class="list-group-item list-group-item-primary">
                <div class="row">
                    <div class="col-md-3">
                    <div class="col-md-3">
                        <label>USD Price</label>
                    <div class="col-md-3">
                        <label>BTC Price</label>
                    <div class="col-md-3">
                        <label>Change in Last Hour</label>
            {% for coin in crypto_data %}
            <div class="list-group-item list-group-item-{% if coin.percent_change_1h.0 == '-'%}danger{% else %}success{% endif %}">
                <div class="row">
                    <div class="col-md-3">
                    <div class="col-md-3">
                    <div class="col-md-3">
                    <div class="col-md-3">
            {% endfor %}

We are using bootstrap.css  for styling. Now if you go to localhost:8000  you can see the details as in below image.

get latest bitcoin and other crypto currencies rates using python django

Complete code is available on Github.

Download and setup the project on your machine. Experiment with it and let us know in case of any query.  

[1] https://coinmarketcap.com/api/
[2] Django 2.0 official documentation
api requests   2   3211

Related Articles:
Sending post request with different body formats in Django
There are a few different formats of the body we can use while sending post requests. In this article, we tried to send post requests to different endpoints of our hello world Django application from the postman. Let's see what is the difference between discussed body formats....
Scraping data of 2019 Indian General Election using Python Request and BeautifulSoup and analyzing it
scraping 2019 election data india, Scraping data of 2019 Indian General Election using Python BeautifulSoup and analyzing it, using beautifulsoup to collection election data, using request...
How to send bulk emails for free using Mailgun and Python Django
How to send bulk emails for free using Mailgun and Python-Django, How to send free promotional emails from your Django application. Free email Api....
Getting query params from request in Django
In this article, we will see how to access the query parameters from a request in the Django view, Accessing GET attribute of request, get() vs getlist() method of request in Django, query parameters Django,...

2 thoughts on 'Get Latest Bitcoin And Other Crypto-Currencies Rates Using Python Django'
Kehinde :
Just what i needed to kickoff

John :
Pls is there away to get the prices of crypto currencies without using coinmarketcap api? I want to have my own standalone.
Admin :
Yes, you can scrape data using requests and beautifulsoup

Leave a comment:

*All Fields are mandatory. **Email Id will not be published publicly.

Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap