Coins: 14,032
Exchanges: 1,073
Market Cap: $2.486T 6.9%
24h Vol: $88.45B
Gas: 7 GWEI
Go Ad-free
API
TABLE OF CONTENTS

How to Fetch Crypto Data Using Python & CoinGecko API (With Examples)

5.0 | by Jackson Henning

Python is one of the most ubiquitous, general-purpose programming languages today, and can be used to create a wide range of varying programs. In this Python API guide, we'll explore how to make API calls in Python toquery CoinGecko API, and retrieve coin price data from the various endpoints:

  • Crypto price /simple/price
  • OHLC /coins/{id}/ohlc
  • Trending /search/trending
  • NFTs /nft/{id}

Let’s dive in!


CoinGecko python api guide

CoinGecko API has a total of 50+ endpoints, of which 30+ are publicly accessible via our Demo API plan. This provides access to independently aggregated crypto data, such as historical and live prices, volume, exchange volumes, contract data, and NFT floor prices – all comprehensively outlined in their API documentation.

If any endpoint is of particular interest to you, simply click the down arrow next to it to reveal the potential parameters associated with that function.

CoinGecko api documentation statust test

The /simple/price endpoint effectively illustrates the functionality of the API. We can input various parameters concerning the coin of interest, the currency to compare it with, whether to include volume/market cap/etc. in our output, and the precision of each price value.

Once we hit ‘execute’, we get a cURL response as follows:

cURL is a command-line tool and library for making HTTP requests. This code language is used to make a GET request to the CoinGecko API, retrieving information about Ethereum (ETH)’s price vs USD. You can perform the same HTTP GET request using Python!

Open a Jupyter notebook, PyCharm, or another favored IDE, by simply typing in the name into the Mac command line ‘Terminal’, such as ‘Jupyter Notebook’. Prior to this, ensure you have Python downloaded, and pip, which is a Python package manager. This process can be mirrored on Windows.

Once you are on your Python script, we will need to import the requests library, which is a commonly used tool for making HTTP requests in Python. By using it, we can facilitate a similar process to that shown before.

import requests
url = ‘https://api.coingecko.com/api/v3/simple/price
params = {  
         ‘ids’: ‘ethereum’,
         ‘vs_currencies’: ‘USD’
}

response = requests.get(url, params = params)
 
In the code example below, 200 refers to a status code, indicating a successful HTTP request. Other status codes might be more familiar, such as code 404 (Not Found), 500 (Internal Server Error), 401 (Unauthorized), and so on. 

To retrieve simple price data, we’d then write:

if response.status_code == 200:
         data = response.json()
         Ethereum_price = data[‘ethereum’][‘usd’]
         print(f’The price of Ethereum in USD is ${Ethereum_price}’)
else:
         print(‘Failed to retrieve data from the API’)

💡 Pro-tip: Make sure you have the ‘requests’ library downloaded in your Python environment. You can install it using pip in your Terminal:

         pip install requests
 

How to Get Coin’s OHLC Data with an API

To pull Open, High, Low, Close (OHLC) data for a cryptocurrency, use the OHLC endpoint /coins/{id}/ohlc in CoinGecko API. The data pulled – the candle's body – has an automatic data granularity for Demo plan users:

  • 1 - 2 days: 30 minutes
  • 3 - 30 days: 4 hours
  • 31 days and beyond: 4 days

Meanwhile, paid API users can enjoy the exclusive daily candle interval parameter, using the 'interval=daily' parameter in your request. The 'daily' interval is available for 1, 7, 14, 30, 90 and 180 days, updated on a 30 minute frequency.

We can utilize the pycoingecko library to pull from this endpoint as it initiates an API request distinct from the one made to the /simple/price endpoint and serves a unique purpose. 

The /coins/{id}/ohlc endpoint can utilize the cg.get_coin_ohlc_by_id method from the pycoingecko library. This method is specifically created to fetch OHLC price data for a given cryptocurrency, in this case Ethereum, over a specified number of days. As it is making a request to a different endpoint, we can use the pycoingecko library to facilitate this:

         from pycoingecko import CoinGeckoAPI
         cg = CoinGeckoAPI()
         ohlc = cg.get_coin_ohlc_by_id(id = “ethereum”, vs_currency = “usd”, days = “30”)
         print (ohlc)

Of course, the print method will, as designed, display JSON data returned by the API. 

In order to make it more palatable, we can utilize pandas DataFrames.


How to Turn Requests into Readable pandas DataFrame

To convert text data to a human-readable pandas DataFrame, first convert the response to a string and then extract key-value pairs as columns.

In the code below, the OHLC variable stores the JSON response data, which is essentially a list of OHLC data points. Each data point is represented as a dictionary. When you create a pandas DataFrame using pd.DataFrame(ohlc), pandas interprets each dictionary within the list as a row in the Dataframe, and extracts the key-value pairs as columns.

         import pandas as pd
         df = pd.DataFrame(ohlc)
 
As the output is still not properly legible, we will make a few further adjustments: labeling columns, converting the date to a pandas datetime object, and setting the date as the index.
         df.columns = [“date”, “open”, “high”, “low”, “close”]

💡Pro-tip: To reconfirm that these data points are accurate, we can return to the CoinGecko website and compare the information.

Let's continue readjusting our DataFrame:

         df[“date”] = pd.to_datetime(df[“date”], unit = “ms”)
         df.set_index(‘date’, inplace = True)

The DataFrame is now complete, featuring OHLC data and accurate datetime stamps, which are all in accordance with the 4-hour automatic granularity for 30 day price history:


How to Fetch Cryptocurrency Price Data 

We can obtain all coins market data by using the /coins/markets CoinGecko API endpoint. The parameters allow us to specify:

  • The currency to compare it to (vs_currency – typically ‘usd’)
  • The ids of specific coins (if we want to narrow down our list)
  • The order
  • The number per page
  • The page number, etc.

Similarly to the /coins/{id}/ohlc endpoint, we can use the pycoingecko library, instead of the requests library (like we did with /simple/price).

parameters = {
         'vs_currency': 'usd',
         'order': 'market_cap_desc',
         'per_page': 100,
         'page': 1,
         'sparkline': False,
         'locale': 'en'
         }
coin_market_data = cg.get_coins_markets(**parameters)
print(coin_market_data)

However, to avoid getting indigestible data, turn the output into a pandas DataFrame as we did before.

To overcome the undue number of columns, we can next employ pandas index slicing!

         df = pd.DataFrame(coin_market_data)
         df = df.drop(['id', 'symbol', 'image', 'high_24h', 'low_24h', 'price_change_24h', 'price_change_percentage_24h',
         'market_cap_change_24h','market_cap_change_percentage_24h', 'fully_diluted_valuation', 'ath_date', 'ath_change_percentage',
         'atl_change_percentage', 'atl_date', 'roi'],  axis = 1)
         df

Continue to readjust the desired area of the DataFrame, dropping columns through ‘df.drop’, whittling it down to the state we want it in:


Using the “requests” library, we will navigate to the /search/trending endpoint to retrieve data on the top 7 trending coins on CoinGecko, as searched by users in the last 24 hours, with the most popular being ordered first.

url = ‘https://api.coingecko.com/api/v3/search/trending’
headers = {
         ‘accept’: ‘application/json’
}
response = requests.get(url, headers = headers)

The ‘accept’ header here is set to ‘application/json’, indicating the client – your Python script – prefers to receive the response in JSON format, which is informed by the ‘header’ to the server. For example, if you prefer to receive the response in XML format, you can set the ‘accept’ header to ‘application/xml’. This can be mirrored for other formats like CSV, HTML, or other media (MIME) types.

Next, write a similar ‘if’ statement, depending on if the request was successful or not. However, as we cannot simply mold this request into a DataFrame, because the resultant arrays we are trying to convert have differing lengths.

Therefore, we need to initialize an empty list where we will store the data for each coin, create a for loop that iterates through the ‘coins’ section of our JSON data, defaulting to an empty list ([]) if the ‘coins’ does not exist. Thereafter, we'll extract the ‘item’ dictionary for each coin, create an empty dictionary if it does not exist, and finally append a dictionary to our list for each coin. The dictionary then contains information regarding the coins ‘id’, ‘name’, ‘symbol’, ‘market_cap_rank’, and ‘score’. The ‘get’ method is used for each key to extract the corresponding value from the dictionary, assigning a default value ‘’ for empty strings or 0 for integers.

if response.status_code == 200:
         # Convert the JSON response to a Python dictionary
         data = response.json()

         # Extract relevant fields from the JSON data (coins section)
         coin_data = []
         for coin in data.get('coins', []):
         coin_item = coin.get('item', {})
         coin_data.append({
         'id': coin_item.get('id', ''),
         'name': coin_item.get('name', ''),
         'symbol': coin_item.get('symbol', ''),
         'market_cap_rank': coin_item.get('market_cap_rank', 0),
         'score': coin_item.get('score', 0)
     })

         # Create a DataFrame from the extracted data
         df = pd.DataFrame(coin_data)

         # Display the DataFrame
         df

else:

         print(f"API request failed with status code: {response.status_code}")

 Our constructed DataFrame should appear as follows:


How to Get NFT Price Data with API

The easiest way to get NFT price data is through the /nft/list and /nft/{id} CoinGecko API endpoints, where you can pull a list of NFT collections and respective data pertaining to that NFT collection.

This can be done with the following Python script:

# Request for list of NFTs
nfts_list = cg.get_nfts_list(per_page=100, page=1)
# View what NFTs are covered and choose one (e.g. Squiggly)
url = 'https://api.coingecko.com/api/v3/nfts/squiggly'
response = requests.get(url)
if response.status_code == 200:
         squiggly_nft = response.json()
         synthesized_data = {
         'id': squiggly_nft['id'],
         'name': squiggly_nft['name'],
         'symbol': squiggly_nft['symbol'],
         'image': squiggly_nft['image'],
         'description': squiggly_nft['description'],
         'native_currency': squiggly_nft['native_currency'],
         'floor_price': squiggly_nft['floor_price'],
         'market_cap': squiggly_nft['market_cap'],
         'volume_24h': squiggly_nft['volume_24h']
         }

         # Create a DataFrame from the synthesized data
         df = pd.DataFrame([synthesized_data])
         df = df.drop(['symbol', 'image', 'id'], axis = 1)
         df

else:

         print("Request failed with status code:", response.status_code)

Essentially, this requests for a list of NFT collections, allowing us to sift through and pick from the available JSON data. Once selected, we append the NFT name to the end of the url (i.e. 'https://api.coingecko.com/api/v3/nfts/squiggly'). Once the response status is successful, simply construct a new flattened data dictionary, selecting desired data and pulling it from the JSON text, before creating a dataframe around our synthesized data!


Unlock Exclusive API Endpoints

Evidently from the above, CoinGecko API provides access to coin prices, NFT activity, trending coins, derivatives, and many others.  Although the data returned is in JSON format, one can easily employ the pandas data science library to convert the response into an easily legible structure. 

To unlock exclusive API endpoints and historical prices, developers, traders and project founders can consider subscribing to our Analyst API plan. The CoinGecko API currently has 50+ endpoints, tracks 10,000+ coins across 800+ exchanges and 3,000+ NFT collections serving billions of API calls each month. If you require a custom solution, fill in the form below to get in touch with our API sales team:


Looking for further API resources? Check out this tutorial that covers 5 popular crypto trading strategies and how you can backtest using historical crypto data.

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Tell us how much you like this article!
Vote count: 7
Jackson Henning
Jackson Henning

Jackson Henning has a background in economics and has spent 3 years in crypto, primarily ensconced in NFTs and DeFi. He is especially intrigued by the perpetual ingenuity common to crypto trading, along with the employment of technical analysis and the ability of DeFi to push the bounds of traditional finance. Follow the author on Twitter @Henninng

More Articles

coingecko
Continue in app
Track prices in real-time
Open App
Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Login to track your favorite coin easily 🚀
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
IT'S FREE! Track your favorite coin easily with CoinGecko 🚀
By continuing, you agree to CoinGecko Terms of Service and acknowledge you’ve read our Privacy Policy
or
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
Didn't receive confirmation instructions?
Resend confirmation instructions
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores