This space is available for advertisement. Please contact us if interested.
Advertise with us
api requests   2   7741
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 startapp bitcoin

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

Project Setup:


Create  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  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  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  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 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 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  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 = ""

        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  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 = ""

        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="" 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.  

[2] Django 2.0 official documentation
api requests   2   7741

Related Articles:
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,...
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...

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.

DigitalOcean Referral Badge

Get a .COM for just $5.98!

© 2021-2022 Python Circle   Contact   Sponsor   Archive   Sitemap   Partner Sites: PythonSnippets.Dev  99Dev.Tools