CoinMarketCap API Python Tutorial (2022)

This CoinMarketCap API Python tutorial explains how you can use the Python Client for CoinMarketCap’s API to track the prices of various crypto assets.

You will see how to call multiple Rest API endpoints of CoinMarketCap API to retrieve cryptocurrency information, such as the latest and historical quote prices, global metrics, fiat prices, etc. You will also study how to import CoinMarketCap data into Excel and Google sheets. 

What Is CoinMarketCap?

CoinMarketCap is the world’s leading price tracking platform that shows runtime statistics for various cryptocurrencies and exchanges. It retrieves prices from various cryptocurrency exchanges and shows the volume-weighted average of all the prices. 

CoinMarketCap updates its endpoints after every minute. So one can say that CoinMarketCap data is in real-time.

How Do I Get Data from CoinMarketCap?

You can get data from CoinMarketCap by either visiting the website or using the CoinMarketCap API to get data from CoinMarketCap. I’ll show you how to do the latter in this post.

But before I discuss that, how do you know if CoinMarketCap is right for you?

Why Should I Use CoinMarketCap?

Following are some of the reasons you should use CoinMarketCap:

  1. It has a free plan.
  2. Easy to use interface.
  3. Tracks a large number of crypto assets and exchanges.
  4. You can earn crypto while learning using the learn-to-earn plan.
  5. Availability of learning tools such as Alexandria.

Why Shouldn’t I Use CoinMarketCap?

  • Lots of negative reviews related to the accuracy of information.
  • Considered biased in favor of Binance.
  • The free plan has severely limited features.

What Can You Do with the CoinMarketCap API?

You can fetch information from CoinMarketCap Rest API in the code written in the programming language of your choice. You can develop your own cryptocurrency price tracking software using the CoinMarketCap API.

Is Using The CoinMarketCap API Free?

CoinMarketCap has a  free basic plan. For more advanced features, you have to subscribe to an advanced plan. The following image depicts a summary of the CoinMarketCap API fees. 

CoinMarketCap Pricing

For more information, see CoinMarketCap API pricing. 

Getting Started with CoinMarketCap API in Python

You need an API Key before making calls to the CoinMarketCap API. 

Sign up for the CoinCapMarketCap Developer Portal Account

You can get your API Key by Signing up with a Free Developer Portal account, as shown in the following screenshot. 

Fill out the form below and click the “CREAT MY ACCOUNT” button.

CoinMarketCap Signup Page

An email containing a verification code will be sent to the email account you used to sign up. Enter the verification code in the following window and click the “CONFIRM SIGNUP” button. 

CoinMarketCap Signup Email Verification Message

How to Get a CoinMarketCap API Key

Once you verify your email, you will be taken to the CoinMarketCap dashboard. You can copy your API key from the box in the top left corner of your dashboard, as shown in the following screenshot. 

CoinMarketCap Dashboard

Simple Example Fetching Data using CoinMarketCap API in Python

There are two ways to make API calls to the CoinMarketCap API:

  1. Using the python-coinmarketcap library
  2. Using the Python requests function. 

You will see both of these approaches in this section.

CoinMarketCap API python-coinmarketcap Library Example

You can install the python-coinmarketcap library via the following command on your terminal.

pip install python-coinmarketcap

Following are the steps to make an API call to the CoinMarketCap API:

  1. Import the coinmarketcapapi module into your Python application.
  2. Create an object of the CoinMarketCapAPI class and pass it your API key.
  3. Using the CoinMarketCapAPI object, call the function for the CoinMarketCap API endpoint that you want to access. For instance, to get the latest currency listings, call the cryptocurrency_listings_lates() function. 

The python-coinmarketcap library functions return a response dictionary that contains response status and the data returned by the API. You can use the `data` attribute to view the data.

The following example demonstrates how to make an API call to the CoinMarketCap API using the python-coinmarketcap library. 

import coinmarketcapapi
import os
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_listings_latest()
print(response.data)

Output:

CoinMarketCap Python API Output Example

Check out the python-coinmarketcap official documentation to see the details of all the functionalities offered by the library.   

CoinMarketCap API Request Function Example

Python wrappers for the CoinMarketCap API can be slow. If speed is a concern, you can use Python’s request function to access the CoinMarketCap API. Here is an example of how to do this.

from requests import Request, Session
from requests.exceptions import ConnectionError, Timeout, TooManyRedirectsimport json
api_key = os.environ['CMC-Key']
url = 'https://pro-api.coinmarketcap.com/'api_call = 'v1/cryptocurrency/listings/latest'

headers = {  'Accepts': 'application/json',  'X-CMC_PRO_API_KEY': api_key,}
session = Session()session.headers.update(headers)
response = session.get(url + api_call)response = json.loads(response.text)
print(response['data'])

Output:

CoinMarketCap Python API Request Method Example Output

In this tutorial, we will be using the python-coinmarketcap library to access the CoinMarketCap API. 

What Are the CoinMarketCap API Endpoints?

CoinMarketCap API endpoints are sets of Rest API calls that allow you to retrieve various information from the CoinMarketCap API. 

CoinMarketCap API functions are categorized into eight top-level endpoints:

  1. Cryptocurrency 
  2. Exchange 
  3. Global Metrics
  4. Tools
  5. Blockchain
  6. Fiat
  7. Partners
  8. Key

Not all the functions from these endpoints are available with the free plan. Look at the API plan feature comparison to learn more about it. 

In this tutorial, you will see how to call the Rest API functions available with the Free plan. You will use the python-coinmarketcap library to make the rest API calls. 

How to Get Data from CoinMarketCap Currency API

The CoinMarketCap API’s Cryptocurrency endpoints contain 17 functions that return various cryptocurrency-related information. Five of these endpoints are free to use, which you will see in this section. 

  • Map
  • Info
  • Latest Market Quotes
  • Latest Market Listings
  • Cryptocurrency Categories

The Python code for accessing the remaining endpoints remains the same. You just have to upgrade your account to access the endpoints. 

How to Obtain Currency Info with CoinMarketCap API

You can use the cryptocurrency_info() function to access various information about a currency. Behind the scenes, the cryptocurrency_info() function makes the /v2/cryptocurrency/info API call to the CoinMarketCap API.

For example, the following script returns the currency info for Bitcoin. 

import coinmarketcapapi
import os
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_info(symbol = 'BTC')
print(response.data['BTC'].keys())

Output:

dict_keys(['id', 'name', 'symbol', 'category', 'description', 'slug', 'logo', 'subreddit', 'notice', 'tags', 'tag-names', 'tag-groups', 'urls', 'platform', 'date_added', 'twitter_username', 'is_hidden', 'date_launched', 'contract_address', 'self_reported_circulating_supply', 'self_reported_tags', 'self_reported_market_cap'])

You can also get currency information about multiple currencies by passing a comma-separated string of currency symbols to the symbol parameter. 

For example, the following code returns currency information for Bitcoin and Ethereum. 

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_info(symbol = 'BTC,ETH')
df = pd.DataFrame.from_records(response.data)
df

Output:

CoinMarketCap API Currenty Info Output

Check out  CoinMarketCap Cryptocurrencies to get a list of all cryptocurrency symbols. 

How to Get Currency Mappings with CoinMarketCap Ids

CoinMarketCap assigns unique ids to all cryptocurrencies. These unique ids can be used to get further cryptocurrency information. 

The cryptocurrency_map() function returns mapping between cryptocurrencies, their unique CoinMarketCap ids, and other relevant currency information.

import coinmarketcapapi
import osimport pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_map()
df = pd.DataFrame.from_records(response.data)
df

Output:

CoinMarketCap API Current Mappings Output

You can retrieve cryptocurrency mappings for specific currencies by passing a comma-separated list of currency symbols to the symbol parameter of the cryptocurrency_map() function. 

Here is an example of how to do this:

import coinmarketcapapi
import osimport pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_map(symbol = 'BTC,ETH')
df = pd.DataFrame.from_records(response.data)df

Output:

CoinMarketCap API Currency Mappings Using Symbol Filter Output

How to Get the Latest CoinMarketCap Market Quotes

The cryptocurrency_quotes_latest() function returns the latest cryptocurrency market quotes. The function accepts a single cryptocurrency symbol or a comma-separated list of currency symbols as values for the symbol parameter.

The following script returns the latest market quotes for Ethereum and Bitcoin. 

import coinmarketcapapi
import osimport pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_quotes_latest(symbol = 'ETH,BTC')
df = pd.DataFrame.from_records(response.data)
df

Output:

CoinMarketCap API Currency Quotes Output

How to Get the Latest CoinMarketCap Market Data Listings

You can use the cryptocurrency_listings_latest() function to retrieve the list of all active cryptocurrencies, along with the latest market info, such as price and volume data. 

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_listings_latest()
df = pd.DataFrame.from_records(response.data)
df

Output:

CoinMarketCap API Latest Currency Listings Output

How to Get CoinMarketCap Cryptocurrency Categories

To get the information about all the coin categories available on CoinMarketCap, you can use cryptocurrency_categories() function. 

The function returns category names, descriptions, volumes, volume change,  market cap, market cap change, average price change, and the number of tokens for all the cryptocurrencies from different categories. 

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_categories()
df = pd.DataFrame.from_records(response.data)df

Output:

CoinMarketCap API Currency Categories Output

You can use the cryptocurrency_category() function to get the details of all the cryptocurrencies within a particular category. You must pass the category id to the cryptocurrency_category() function. 

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.cryptocurrency_category( id = '62fe5eb097edc244f4716518')
df = pd.DataFrame.from_records(response.data)
df

Output:

CoinMarketCap API Currency Categories Id Filter Output

Note: Historical data can also be retrieved but not with the basic plan!

How to Get CoinMarketCap Fiat Currency Info

The fiat_map()  from the python-coinmarketcap library calls the  Fiat endpoint from the CoinMarketCap API  to retrieve information about fiat currencies on CoinMarketCap. Here is an example. 

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.fiat_map()
df = pd.DataFrame.from_records(response.data)
df

Output:

CoinMarketCap API Fiat Currency Map Output

How to Get CoinMarketCap Exchange Data

The CoinCapMarket API’s Exchange Endpoint offers functionalities to get various information about cryptocurrency exchanges. None of the functions are available with the free plan. 

The following table contains the list of functions offered by the CoinMarketCap API’s exchange endpoint. 

python-coinmarket library functionRest API CallDescriptionAPI Plan
exchange_map()/exchange/mapReturns a list of all active cryptocurrencies, including their CoinMarketCap IdsBasic
exchange_info()/exchange/infoReturns static metadata for one or more exchanges at CoinMarketCapBasic
exchange_listings_latest()/exchange/listings/latestReturns latest listings for all cryptocurrency exchanges at CoinMarketCapStandard
exchange_listings_historical()/exchange/listings/historicalReturns historical listings for an exchange based on time and interval parameters Standard
exchange_quotes_latest()/exchange/quotes/latestReturns aggregate of latest market data for one or more exchangesStandard
exchange_quotes_historical()/exchange/quotes/historicalReturns historical quotes for an exchange based on time and interval parameters Standard
exchange_marketpairs_latest()/exchange/market-pairs/latestReturns active market pairs for an exchange that CoinMarketCap tracks Standard

How to Get CoinMarketCap GLobal Market Data

The CoinMarketCap’s Global-Metric endpoint returns global market data information. The endpoint offers two functionalities:

  1. Latest Global Metrics
  2. Historical Global Metrics

You can only retrieve the latest global metrics with the free API plan. You will need to upgrade to the standard plan for historical global metrics.

The global_metrics_quotes_latest() function returns the global data quotes. 

import coinmarketcapapi
import osimport pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.globalmetrics_quotes_latest()
response.data

Output:

CoinMarketCap API Global Metrics Quote Output

How to Get CoinMarketCap Tools Data

The Tool endpoint contains tools for price conversion and converting data into the postman format. 

How to Convert Cryptocurrency Prices with CoinMarketCap API?

You can convert cryptocurrency prices using the tools_priceconversion() function. You must pass the cryptocurrency quantity, symbol, and target currency.

For example, the following script demonstrates how you can convert 1 Ethereum to US dollars. 

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.tools_priceconversion(amount = 1, symbol = 'ETH', convert = 'USD')
response.data

Output:

CoinMarketCap API Price Conversion Output

How to Get CoinMarketCap API Key Usage

The CoinMarketCap API’s key endpoint returns API key usage statistics. 

The key_info() function returns your API usage details such as daily request limits, number of requests in the current minute, day, month, etc. 

Here is an example:

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.key_info()
response.data

Output:

CoinMarketCap API Key Usage Stats Output

How to Get CoinMarketCap Partners Data

The CoinMarketCap API contains various partner endpoints you can use to get cryptocurrency information.

For example, you can retrieve a paginated list FCAS (Fundamental Crypto Asset Score) scores  for all the cryptocurrencies using the partners_flipsidecrypto_fcas_listings_latest() function. 

The FCAS score is a comparative metric that determines the relative health of a cryptocurrency.

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.partners_flipsidecrypto_fcas_listings_latest()
df = pd.DataFrame.from_records(response.data)
df

Output:

CoinMarketCap API Get Partners Data Output

How to Extract CoinMarketCap Data to Excel

You can easily extract the CoinMarketCap data to Excel using Python. 

To do so, you can pull the CoinMarketCap data into a Pandas dataframe, as you saw in the previous section.

After that, you can use the to_excel() function from the Pandas dataframe to write the data into an excel file. You need to pass the name of the excel file as input to the to_excel() function.

 The following code demonstrates how to do this:

import coinmarketcapapi
import os
import pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.fiat_map()
df = pd.DataFrame.from_records(response.data)
df.to_excel("D:\Datasets\output.xlsx", sheet_name='Sheet_name_1')

Output:

CoinMarketCap API Data to Excel

How to Pull CoinMarketCap Data into Google Sheets?

You can again take the help of Pandas dataframes to pull CoinMarketCap data into google sheets.

To do so, you will need three Python libraries:

  1. Pandas 
  2. gspread
  3. df2gspread

The first step is to import the CoinMarketCap data into a Pandas dataframe using the CoinMarketCap API functions, as shown in the following script. 

import pandas as pd
# pip install gspread
import gspread
#pip install df2gspread
from df2gspread import df2gspread
from oauth2client import service_account
import coinmarketcapapiimport osimport pandas as pd
api_key = os.environ['CMC-Key']
cmc_client = coinmarketcapapi.CoinMarketCapAPI(api_key)
response = cmc_client.fiat_map()
df = pd.DataFrame.from_records(response.data)

Next, you must connect to Google spreadsheets from your Python application. To do so, you need a JSON file containing an API key that allows you to connect your Google spreadsheet account. 

The process to obtain an API key from your Google account is explained on the official documentation page of gspread library.

Once you download the API key, you need to authenticate your credentials which you can do  using the following script:

scope = ['https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive']
credentials = service_account.ServiceAccountCredentials.from_json_keyfile_name('D:\Datasets\my-project-xxxxxxxxxxxxx-xxxxxxxxxxx.json', scope)
gc = gspread.authorize(credentials)

Finally, you can pull the data from the Pandas dataframe into Google sheets using the upload() method from the df2gspread module, as shown in the following script. 

spreadsheet_key = os.environ['GSS-Key']
sheet_name = 'Sheet1'df2gspread.upload(df, spreadsheet_key, sheet_name, credentials=credentials, row_names=True)

Here is your imported fiat currency information in Google Sheets. 

CoinMarketCap API Data to Google Sheets

CoinMarketCap Errors and Rate Limits

Rate Limits

The CoinMarketCap API rate limit depends mainly on your API plan. You will get an HTTP 429 error if you exceed the number of API requests allowed with your API plan.

Errors

JSON response from all the CoinMarketCap API functions contains a status object. You can refer to the status object’s error code or error_message property to view the error’s details. 

Check out  CoinMarketCap API rate limits and error codes for more information.

 Frequently Asked Questions

 Is CoinMarketCap a Wallet?

CoinMarketCap is not a wallet. It is only used for price-tracking of crypto assets.

Can You Withdraw Money from CoinMarketCap?

You cannot directly withdraw money from CoinMarketCap. You need a wallet to withdraw any crypto asset earned at CoinMarketCap.

Why Is CoinMarketCap’s Price Different?

There are three main reasons that prices differ on various Crypto asset tracking websites, e.g., CoinMarketCap:

  1. Liquidity
  2. Trading inefficiencies across exchanges
  3. Average Estimate pricing 

Can I Buy and Sell on CoinMarketCap?

You cannot directly buy or sell on CoinMarketCao. You need to connect a Wallet, e.g., Binance.

Can I Trust CoinMarketCap?

User reviews suggest that CoinMarketCap is not a very trustworthy site. Many users blame CoinMarketCap for being biased towards Binance (its parent organization) and for providing misinformation. 

Conclusion

CoinMarketCap is the world’s leading crypto price tracking website aggregating real-time information from most cryptocurrency exchange platforms. CoinMarketCap also offers a feature-rich Rest API you can employ to extract cryptocurrency data using code.

This tutorial shows how the Python client for CoinMarketCap API fetches information from CoinMarketCap. You saw how to use the python-coinmarketcap library and the Python requests method to call CoinMarketCap API. You can build upon the knowledge learned in this tutorial to create your price tracking software in Python. 

Leave a Comment