Coinmarketcap API with Python

Please follow and like us:

Web APIs or application programming interfaces allow you to send input and get output from a web application. The output they create is frequently in the form of a JSON string.

APIs usually have some limits. In this way, the Coinmarketcap API is no exception. The free version of the Coinmarketcap API allows up to 30 calls per minute, 10000 calls per month, and 333 calls per day. The company also offers various other paid plans that enable more API calls.

Coinmarketcap gives users ways of getting data about multiple cryptocurrencies with a single call. I will discuss this later.

You can find the code for this tutorial at: https://github.com/scottcm73/coinmarketcap_api_tutorial

For this tutorial, first, you need to sign up for Coinmarketcap’s API.

https://coinmarketcap.com/api/

Then, you will get an API key. Be sure to copy and paste this key and not try to type it out.

I recommend that you start a new file in your code editor of choice (mine is VSCode). Call this file coinmarketcapapi.env.

Copy and paste the line,

export COINMARKETCAP_API_KEY = ‘your key’

Then save it as coinmarketcapapi.env.

Now, create a .gitignore file (a text file with the full name .gitignore. (Note the period before the file name).

In the last line of the .gitignore file, type:

*.env

Again, I also covered this in the previous article.

Below is the a link to the API’s documentation.

https://coinmarketcap.com/api/documentation/v1/

As with most API’s, you will need to work with the request module and the json object.

So, the following is needed as part of the import section.

NOTE: os, json, pprint, and requests are part of the standard python library, and they does not require installation with pipenv.

Set the variable key equal to the environment variable COINMARKETCAP_API_KEY.

key=os.environ.get('COINMARKETCAP_API_KEY')

You will also want to set up pretty print to print json response with nice indentation.

pp = pprint.PrettyPrinter(indent=4)

Then copy and paste the following to test your API key.

url = f'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
print(url)
headers = {
    'Accepts': 'application/json',
    'X-CMC_PRO_API_KEY': key,
}
parameters = {
'id':'1,2,3,4'

}

session = Session()
session.headers.update(headers)
try:
    response = session.get(url, params=parameters)
    data = json.loads(response.text)
    pp.pprint(data)
    

except (ConnectionError, Timeout, TooManyRedirects) as e:
    data = json.loads(response.text)
    pp.pprint(data)

Save the file as cmtest.py

Open the terminal window if you haven’t already. Navigate to the folder with your project.

Set the environment variable, COINMARKETCAP_API_KEY with the following command in the terminal (command line).

export COINMARKETCAP_API_KEY = ‘your key’

Be sure to change ‘your key’ to the key that the API signup procedure gave you.

Finally, it is time to test to see if you can connect with the API. Type the following in the command line.

python cmtest.py

You should see something print out in the terminal. If you get an error, the most likely scenario is that you forgot to set COINMARKETCAP_API_KEY with the export command.

Double-check COINMARKETCAP.com to see if the API key they have for you is the one you copied.

Once you have the API working, you can change the URL to get only the information you want.

The documentation points out that you can get information about multiple cryptocurrencies in a single API call.

You send a list of crypto id numbers without spaces at the end of the URL.

Changing the URL to:

url = f'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'

Save the file. Then type try running the program again.

You should get information about the cryptocurrencies with the id numbers listed at the end of the URL.

Next, make a list of the cryptocurrency ids numbers that you want information about.

Open a new file in your code editor. Then copy and paste the following code that creates a CSV file with the id number, the name of the cryptocurrency, and the symbol(capitalized abbreviation such as BTC for Bitcoin).

# Run this file by itself to produce the csv with coin ids, symbols, and names
# Then put the created file, coinmap.txt into the static folder.

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirects
import json
import pprint
import os

import csv

pp = pprint.PrettyPrinter(indent=4)


# This creates a long string of all the top 100 crypto currency symbols.
symbolstr=','.join(('BTC,ETH,BNB,XRP,USDT,ADA,DOT,UNI,LTC,LINK,XLM,BCH', 
        'THETA,FIL,USDC,TRX,DOGE,WBTC,VET,SOL,KLAY,EOS,XMR,LUNA', 
        'MIOTA,BTT,CRO,BUSD,FTT,AAVE,BSV,XTZ,ATOM,NEO,AVAX,ALGO', 
        'CAKE,HT,EGLD,XEM,KSM,BTCB,DAI,HOT,CHZ,DASH,HBAR,RUNE,MKR,ZEC',
        'ENJ,DCR,MKR,ETC,GRT,COMP,STX,NEAR,SNX,ZIL,BAT,LEO,SUSHI', 
        'MATIC,BTG,NEXO,TFUEL,ZRX,UST,CEL,MANA,YFI,UMA,WAVES,RVN',
        'ONT,ICX,QTUM,ONE,KCS,OMG,FLOW,OKB,BNT,HNT,SC,DGB,RSR,DENT',
        'ANKR,REV,NPXS,VGX,FTM,CHSB,REN,IOST,BTMX,CELO,PAX,CFX'))
    
# Makes symbolstr into a list for later for loop
symbol_list=symbolstr.split(',')
key=os.environ.get('COINMARKETCAP_API_KEY')

url= f'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
print(url)
headers = {
    'Accepts': 'application/json',
    'X-CMC_PRO_API_KEY': key,
}
parameters = {
  'symbol':symbolstr
  }
session = Session()
session.headers.update(headers)

try:
    response = session.get(url, params=parameters)
    data = json.loads(response.text)

except (ConnectionError, Timeout, TooManyRedirects) as e:
    data = json.loads(response.text)

pp.pprint(data)
file_to_open='coinmap.txt'
line_list=[]
with open(file_to_open, 'w') as this_csv_file:
  
    for symbol in symbol_list:
        
        thename=data['data'][symbol]['name']
        cid=data['data'][symbol]['id']

        line=f'{cid}, {thename}, {symbol}'
        line_list.append(line)

    for line in line_list:
        this_csv_file.write(line)
        this_csv_file.write('\n')

Save the file as makecoinidcsv.py.
Run this file in particular, and you should get a CSV file called coinmap.txt.

You can use this later to call for the cryptocurrencies by their ids (as the API documentation recommends).

Go back to edit cmtest.py.

From looking at the CSV you created, make a list of the cryptocurrency ids about which you want information. (For example, Bitcoin, BTC is 1.)

Call this list cid_list.

cid_list=[1, 3, 27, 54]

Then copy and paste the following after the line above and before setting the url.

def list_to_str(cid_list):
    cid_list=list(set(cid_list)) #cid_list is the list of ids from the csv file.
    the_cid_list=[int(value) for value in cid_list]
    cid_list_str = str(the_cid_list)[1:-1] #This eliminates the [brackets around the list
    cid_list_str=cid_list_str.replace(', ', ',').replace(' ,',',') 
#This eliminates the spaces before or after each comma.
    return cid_list_str

Now, set cid_list_str equal to the result of the list_to_str function with cid_list as the parameter.

cid_list_str=list_to_str(cid_list)

You will now use an f string to set the url value.
Change the url setting line to:

  url = f'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?convert=USD&id={cid_list_str}'

In this example f string command inserts the value within the curly brackets into the string at the end.

Now when you run cmtest.py you will get data about each of the id numbers in the list.

Please follow and like us: