Fetch real-time Cryptocurrency data using Python

Hello programmers, in this tutorial, we will learn how to fetch real-time cryptocurrency data using Python.

A cryptocurrency is a unit of currency that uses cryptographic algorithms. This currency does not exist in physical form like paper money. It is known as digital currency, which is used for transactions via computer networks without relying on government policies or banks. This currency is kept track and monitored using a secure network called a blockchain.

Popular cryptocurrencies in today’s world include:

  • Bitcoin
  • Ethereum
  • Litecoin

Many people transact amounts in the form of bitcoins. For this purpose, people usually check the current bitcoin value in the market and do the transaction accordingly.

We can fetch the real-time cryptocurrency data using python to meet our requirements.

CoinDesk API

An API (Application Programming Interface) is used to make connections between different computers for a specific purpose.

CoinDesk stores different information about Bitcoins and refreshes itself every minute to show the data in the form of USD, GBP, and EUR.

CoinDesk API is accessible using various programming languages. We get the data in JSON format and print the required information required as per the user’s requirements.

CoinDesk API in Python to fetch real time crypto data

Given below is an illustration of how to use the CoinDesk API and get the required information.

#Importing necessary libraries
import requests

def getBitcoinValue():
    #Getting the data from the API
    url = 'https://api.coindesk.com/v1/bpi/currentprice.json'
    response = requests.get(url)
    data = response.json()
    #Getting the req information from API
    for currPrice in data['bpi'].values():
        print(f"{currPrice['code']} : {currPrice['rate']} {currPrice['description']}")

if __name__ == "__main__":
    getBitcoinValue() #calling the function

Output

USD : 25,478.0445 United States Dollar
GBP : 20,686.1084 British Pound Sterling
EUR : 24,218.6648 Euro

Explanation

We first import the “request” library which will be necessary to get the data from the API. Inside the getBitcoinValue() function, we call the API and get the current bitcoin values. From the JSON formatted data, we print the bitcoin current values in three units of currencies shown above. We call the function at the start of the file.

Leave a Reply

Your email address will not be published. Required fields are marked *