javascript - Unable to Fetch Coinmarketcap API data - Stack Overflow
Stack Overflow
About
Products
For Teams
Stack Overflow
Public questions & answers
Stack Overflow for Teams
Where developers & technologists share private knowledge with coworkers
Talent
Build your employer brand
Advertising
Reach developers & technologists worldwide
Labs
The future of collective knowledge sharing
About the company
Loading…
current community
Stack Overflow
help
chat
Meta Stack Overflow
your communities
Sign up or log in to customize your list.
more stack exchange communities
company blog
Log in
Sign up
Home
Questions
Tags
Users
Companies
Labs
Discussions
New
Collectives
Explore Collectives
Teams
Stack Overflow for Teams
– Start collaborating and sharing organizational knowledge.
Create a free Team
Why Teams?
Teams
Create free Team
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
Get early access and see previews of new features.
Learn more about Labs
Unable to Fetch Coinmarketcap API data
Ask Question
Asked
2 years, 5 months ago
Modified
1 year, 11 months ago
Viewed
2k times
1
This error:
Access to fetch at
'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
from origin 'http://localhost:19006' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource
...is returned by this fetch request.
fetch(
"https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest",
{
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Headers":
"'Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'",
"Content-Type": "application/json",
"X-CMC_PRO_API_KEY": API_KEY,
},
}
)
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.error(error));
Why is this happening?
javascriptreact-nativeapiexpocoinmarketcap
Share
Improve this question
Follow
edited Oct 16, 2021 at 11:02
It'sNotMe
1,22211 gold badge1111 silver badges3232 bronze badges
asked Oct 15, 2021 at 6:19
Harsh MittalHarsh Mittal
4911 gold badge11 silver badge88 bronze badges
1
2
coinmarketcap.com/api/faq/….
– bamtheboozle
Oct 15, 2021 at 6:22
Add a comment
|
1 Answer
1
Sorted by:
Reset to default
Highest score (default)
Trending (recent votes count more)
Date modified (newest first)
Date created (oldest first)
0
1- send request to your backend processing file system (php,cfm,aspx) etc
2- use curl to process your api and send it via your backend code, do not use javascript to fetch "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest" instead use "http://yourdomain.com/yourendpoint"
3- now at your end point use your backend tech to hit "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest" via curl
Share
Improve this answer
Follow
edited Apr 7, 2022 at 9:54
Mike Yang
2,65933 gold badges2424 silver badges2828 bronze badges
answered Oct 15, 2021 at 6:45
Jawwad AhmedJawwad Ahmed
31722 silver badges1111 bronze badges
Add a comment
|
Your Answer
Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more
Thanks for contributing an answer to Stack Overflow!Please be sure to answer the question. Provide details and share your research!But avoid …Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.To learn more, see our tips on writing great answers.
Draft saved
Draft discarded
Sign up or log in
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Submit
Post as a guest
Name
Required, but never shown
Post as a guest
Name
Required, but never shown
Post Your Answer
Discard
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Not the answer you're looking for? Browse other questions tagged javascriptreact-nativeapiexpocoinmarketcap or ask your own question.
The Overflow Blog
How Stack Overflow is partnering with Google to encourage socially...
Featured on Meta
Our partnership with Google and commitment to socially responsible AI
Shifting the data dump schedule: A proposal
2024 Community Moderator Election Results
Temporary policy: Generative AI (e.g., ChatGPT) is banned
Related
0
react-native fetch data from REST Api fails
0
Fetching data from API failed
0
React component is unable to fetch data from api
2
React / Axios: fetch API data with key for CoinMarketCap
2
React Native fetch API response not displaying
0
cannot display fetched api data in ReactJS
1
can't seem to retrieve data from this api in react
0
I can't get data from api to react
0
React: cant get data via API
0
React Native - Cannot fetch API
Hot Network Questions
Is there some kind of law that even if data is legally compiled from public sources, it is illegal to collect too much and share it?
I do not understand behavior of current in 74HC4066
Copy a folder name into the name of its files
PTIJ: Are we allowed to eat talking animals?
What is the difference between "pretty" and "handsome" in this context?
Is my queue table implementation race condition safe?
Quote with left indent only
Property of the Hamiltonian's discrete spectrum
Egypt hotel deliberately overcharged dollar payments and refunded the difference in cash. Why?
Deleting Software I Wrote Upon Leaving Employment of a Company
Creating a one sided buffer in QGIS
80s novel. A canine-headed humanoid alien unexpectedly steps out from transportation portal
Was the Holtzman Shield gas permeable?
What was the total army strength of the Byzantine empire under Justinian?
Apex Built-in Counter Class?
What would an “unmanipulated election” look like?
Is utilizing a singleton for a cache an antipattern?
What do "fünf Tage Dicken" and "fünf Tage Kahn" mean in All Quiet on the Western Front?
Ex-advisor wants to publish my work in a journal I don't like
What is this large device labelled 'Telefunken Datenspeicher' and how does it work?
Is there a word to describe that somebody changed their mind (like "doch nicht")?
To copy a file and preserve its comment
Shunting yard calculator in C
Safe, easy way to tap into taut NM cable in wall?
more hot questions
Question feed
Subscribe to RSS
Question feed
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
lang-js
Stack Overflow
Questions
Help
Products
Teams
Advertising
Collectives
Talent
Company
About
Press
Work Here
Legal
Privacy Policy
Terms of Service
Contact Us
Cookie Settings
Cookie Policy
Stack Exchange Network
Technology
Culture & recreation
Life & arts
Science
Professional
Business
API
Data
Blog
Site design / logo © 2024 Stack Exchange Inc; user contributions licensed under CC BY-SA. rev 2024.3.14.6266
token invalid coinmarketcap-掘金
首页 首页
沸点
课程
直播
活动
竞赛
商城
APP
插件 搜索历史
清空
创作者中心
写文章 发沸点 写笔记 写代码 草稿箱 创作灵感
查看更多
会员
登录
注册
token invalid coinmarketcap CoinMarketCap是一个非常流行的加密货币数据分析网站,它允许用户跟踪加密货币的价格、市值和其他指标。如果您在使用CoinMarketCap时遇到“token invalid”错误,这通常表示您的API密钥已过期或无效。
要解决这个问题,您可以尝试以下几个步骤:
检查您的API密钥是否过期或无效。如果您的API密钥已过期,您需要更新您的密钥。如果您的API密钥无效,则需要创建一个新的API密钥。
确保您正在使用正确的API端点。CoinMarketCap有多个API端点,例如/pro、/v1、/v2等,具体取决于您正在使用的API版本。如果您使用了错误的API端点,也可能导致“token invalid”错误。
检查您的API调用是否符合CoinMarketCap的要求。例如,一些API需要您提供特定的参数或HTTP标头,如果您的API调用没有正确地包含这些内容,则可能会导致“token invalid”错误。
如果您仍然无法解决“token invalid”错误,建议您查看CoinMarketCap的API文档,或者联系CoinMarketCap支持团队以获取帮助。 【Humo】小趴菜系列-CoinMarketCap第一弹 获取历史货币数据 【Humo】小趴菜系列-CoinMarketCap第一弹 获取历史货币数据 嘿,兄die,我是小右。交个朋友吧~
Mini_Right
1年前
224
点赞
评论
后端
【Humo】小趴菜系列-CoinMarketCap第二弹-获取货币历史数据 【Humo】小趴菜系列-CoinMarketCap第二弹-获取货币历史数据 嘿,兄die,我是小右。交个朋友吧~
Mini_Right
1年前
278
点赞
评论
后端
失业中 swiftUI json数据解析 和模型数据,网络请求 https://app.quicktype.io/ model数据 网络请求封装 请求 数据与模型数据交互 页面显示
undefined在掘金39041
3月前
21
点赞
评论
CSS
登链钱包(一款功能强大的以太坊钱包)完全开源 登链钱包完全开源,登链钱包完全开源,登链钱包完全开源,重要的事情说三遍。 再也不用傻乎乎找人开发以太坊钱包了, 直接拿去用吧;再也不用担心私钥会被上传到别人的服务器上。 区块链是开放的,很难想象一个封闭的项目如何产生信任,开源一直是区块链社区所倡导的行为准则。 我们也希望开源能…
深入浅出区块链
5年前
846
点赞
评论
以太坊
使用 JavaScript 和 CloudKit 获取区块链市场行情 利用 Apple 提供的 CloudKit JS 来获取区块链行情
iCell爱学习27067
6年前
1.6k
6
评论
iOS
给Python初学者的最好练手项目 有很多朋友问我学习了Python后,有没有什么好的项目可以练手。 其实,做项目主要还是根据需求来的。但是对于一个初学者来说,很多复杂的项目没办法独立完成,因此博主挑选了一个非常适合初学者的项目,内容不是很复杂,但是非常有趣,我相信对于初学者小白来说是再好不过的项目了。 这个项目…
Python数据科学
5年前
12k
152
5
后端
Python
微信
跨市场套利怎么操作 跨市场套利是最早在加密资产市场上出现的套利策略,又称为“搬砖”,其主要原理就是通过不同市场间的相同币种的价格差异进行买低卖高获取收益。 根据Coinmarketcap 统计,目前数字货币的币种数量达到5,154个,数字货币交易所达到20,636个,且大部分都是7*24小时交易,…
邓建东
3年前
679
点赞
评论
区块链
PHP写个网页小工具来监控你的加密币 编写一个网页小工具来监控你的加密币投资组合的价值,只需要非常简单的PHP和HTML技能就行。 文章目的超级简单,但我认为可能有很多人会加入加密货币的投资,在某个地方拥有一个网站,并想建立一个私人(或者hell,也许是public)页面在某个地方实时显示你的加密投资组合的价值。但…
jimilai
5年前
1.4k
5
1
PHP
区块链
以太坊
Filecoin Spec 翻译 ——【2.3】 VM - 虚拟机(下) 星际联盟提供对Filecoin Spec 的全文翻译,便于Filecoin项目广大中国参与者理解Filecoin的深层原理。文章将定期更新章节,请持续关注"IPFS星际联盟"&"星际联盟Filecoin"公众号。 RewardActor是保存未铸造的Filecoin代币的地方。…
IPFS星际联盟
3年前
1.3k
1
评论
区块链
ccxt - 一个支持超过百种数字货币交易开源库 | 支持 JavaScript, Python 和 PHP 语言 A JavaScript / Python / PHP library for cryptocurrency trading and e-commerce with support for many bitcoin/ether/altcoin exchange markets …
阴明
5年前
3.8k
28
评论
API
JavaScript
PHP
Reddit - Dive into anything
Skip to main content
Open menu
Open navigation
Go to Reddit Home
r/CoinMarketCap
A chip
A close button
Get app
Get the Reddit app
Log In
Log in to Reddit
Expand user menu
Open settings menu
Log In / Sign Up
Advertise on Reddit
Shop Collectible Avatars
Get the Reddit app
Scan this QR code to download the app now
Or check it out in the app stores
Go to CoinMarketCap
r/CoinMarketCap
r/CoinMarketCap
This is the CoinMarketCap subreddit for all things related to crypto data, exchanges, liquidity, news, education, and more!
Members
Online
•
Zealousideal_Book151
ADMIN
MOD
Token Invalid error crashing CMC iPhone app when going from home to portfolio. Unable to see portfolio.
My portfolio crashes and says ‘Token Invalid’
iPhone 12 Pro Max iOS 14.2
Uninstalled app and reinstalled
Logged out and back in.
I can see portfolio if I login on browser
Any ideas?
Thank you
Read more
Top 3%
Rank by size
Top Posts
reReddit: Top posts of June 14, 2021
reReddit: Top posts of June 2021
reReddit: Top posts of 2021
TOPICS
Gaming
Valheim
Genshin Impact
Minecraft
Pokimane
Halo Infinite
Call of Duty: Warzone
Path of Exile
Hollow Knight: Silksong
Escape from Tarkov
Watch Dogs: Legion
Sports
NFL
NBA
Megan Anderson
Atlanta Hawks
Los Angeles Lakers
Boston Celtics
Arsenal F.C.
Philadelphia 76ers
Premier League
UFC
Business
GameStop
Moderna
Pfizer
Johnson & Johnson
AstraZeneca
Walgreens
Best Buy
Novavax
SpaceX
Tesla
Crypto
Cardano
Dogecoin
Algorand
Bitcoin
Litecoin
Basic Attention Token
Bitcoin Cash
Television
The Real Housewives of Atlanta
The Bachelor
Sister Wives
90 Day Fiance
Wife Swap
The Amazing Race Australia
Married at First Sight
The Real Housewives of Dallas
My 600-lb Life
Last Week Tonight with John Oliver
Celebrity
Kim Kardashian
Doja Cat
Iggy Azalea
Anya Taylor-Joy
Jamie Lee Curtis
Natalie Portman
Henry Cavill
Millie Bobby Brown
Tom Hiddleston
Keanu Reeves
RESOURCES
About Reddit
Advertise
Help
Blog
Careers
Press
Communities
Best of Reddit
Topics
Content Policy
Privacy Policy
User Agreement
Reddit, Inc. © 2024. All rights reserved.
All the time, any time.Please keep me updated by email with the latest crypto news, research findings, reward programs, event updates, coin listings and more information from CoinMarketCap.SubscribeProductsCMC LabsChatGPT PluginCrypto APICrypto IndicesDoodlesSitemapAdvertiseCompanyAbout usTerms of usePrivacy PolicyCookie preferencesCookie policyCommunity RulesDisclaimerMethodologyCareersWe’re hiring!SupportRequest FormContact SupportFAQGlossarySocialsX (Twitter)CommunityTelegramInstagramFacebookRedditLinkedIn© 2024 CoinMarketCap. All rights reserved
coinmarketcap app token invalid-掘金
首页 首页
沸点
课程
直播
活动
竞赛
商城
APP
插件 搜索历史
清空
创作者中心
写文章 发沸点 写笔记 写代码 草稿箱 创作灵感
查看更多
会员
登录
注册
coinmarketcap app token invalid 如果你在使用 CoinMarketCap 应用程序时遇到“token invalid”(无效令牌)错误,这可能是因为你的访问令牌已过期或不正确。
为了解决此问题,你可以尝试以下步骤:
确保你使用的是最新版本的 CoinMarketCap 应用程序。你可以尝试在应用商店或官方网站上查找更新版本并安装它。
如果你使用的是 API,那么请检查你的访问令牌是否正确。你可以登录到 CoinMarketCap 的网站并生成新的访问令牌,然后使用新的访问令牌进行访问。
如果以上两个步骤都没有解决问题,那么请联系 CoinMarketCap 的客服支持团队,他们将帮助你进一步排查问题并提供解决方案。
希望这些信息能够帮到你。如果你还有其他问题,请随时提出。 【Humo】小趴菜系列-CoinMarketCap第一弹 获取历史货币数据 【Humo】小趴菜系列-CoinMarketCap第一弹 获取历史货币数据 嘿,兄die,我是小右。交个朋友吧~
Mini_Right
1年前
224
点赞
评论
后端
【Humo】小趴菜系列-CoinMarketCap第二弹-获取货币历史数据 【Humo】小趴菜系列-CoinMarketCap第二弹-获取货币历史数据 嘿,兄die,我是小右。交个朋友吧~
Mini_Right
1年前
278
点赞
评论
后端
失业中 swiftUI json数据解析 和模型数据,网络请求 https://app.quicktype.io/ model数据 网络请求封装 请求 数据与模型数据交互 页面显示
undefined在掘金39041
3月前
21
点赞
评论
CSS
使用 JavaScript 和 CloudKit 获取区块链市场行情 利用 Apple 提供的 CloudKit JS 来获取区块链行情
iCell爱学习27067
6年前
1.6k
6
评论
iOS
给Python初学者的最好练手项目 有很多朋友问我学习了Python后,有没有什么好的项目可以练手。 其实,做项目主要还是根据需求来的。但是对于一个初学者来说,很多复杂的项目没办法独立完成,因此博主挑选了一个非常适合初学者的项目,内容不是很复杂,但是非常有趣,我相信对于初学者小白来说是再好不过的项目了。 这个项目…
Python数据科学
5年前
12k
152
5
后端
Python
微信
登链钱包(一款功能强大的以太坊钱包)完全开源 登链钱包完全开源,登链钱包完全开源,登链钱包完全开源,重要的事情说三遍。 再也不用傻乎乎找人开发以太坊钱包了, 直接拿去用吧;再也不用担心私钥会被上传到别人的服务器上。 区块链是开放的,很难想象一个封闭的项目如何产生信任,开源一直是区块链社区所倡导的行为准则。 我们也希望开源能…
深入浅出区块链
5年前
846
点赞
评论
以太坊
【翻译】如何在React中使用async/await (componentDidMount Async) create-react-app 构建的项目支持开箱即用。 但是如果你想在自己搭建的webpack配置的项目中使用,你可能会遇到 regeneratorRuntime is not defined 的异常错误。 如果你遇到了这个错误还想在React中使用async/await,…
PeterYuan
5年前
15k
19
2
React.js
前端
Promise
如何使用Express.js、Node.js和Cheerio构建网络搜刮器 在靠近用户的地方部署容器 本工程教育(EngEd)计划由科支持。 在全球范围内即时部署容器。Section是经济实惠、简单而强大的。 免费入门。 如何使用Express.js、Node.js和Chee
DebugUsery
1年前
163
点赞
评论
前端
学习Python后,有什么项目可以练手? 有很多朋友问我学习了Python后,有没有什么好的项目可以练手。 其实,做项目主要还是根据需求来的。但是对于一个初学者来说,很多复杂的项目没办法独立完成,因此博主挑选了一个非常适合初学者的项目,内容不
皮克pik
2年前
198
4
评论
前端
学习了Python后,有什么好的项目可以练手。 有很多朋友问我学习了Python后,有没有什么好的项目可以练手。 其实,做项目主要还是根据需求来的。但是对于一个初学者来说,很多复杂的项目没办法独立完成,因此博主挑选了一个非常适合初学者的项目,内容不
皮克pik
2年前
176
2
评论
前端
Using the CoinMarketCap API: A Beginner's Guide · GitHub
Skip to content
All gists
Back to GitHub
Sign in
Sign up
Sign in
Sign up
You signed in with another tab or window. Reload to refresh your session.
You signed out in another tab or window. Reload to refresh your session.
You switched accounts on another tab or window. Reload to refresh your session.
Dismiss alert
Instantly share code, notes, and snippets.
SrNightmare09/coinmarketcap-api.md
Last active
March 12, 2024 08:20
Star
20
You must be signed in to star a gist
Fork
6
You must be signed in to fork a gist
Star
You must be signed in to star a gist
Code
Revisions
20
Stars
20
Forks
6
Embed
Embed
Embed this gist in your website.
Share
Copy sharable link for this gist.
Clone via HTTPS
Clone using the web URL.
Learn more about clone URLs
Clone this repository at <script src="https://gist.github.com/SrNightmare09/c0492a8852eb172ebea6c93837837998.js"></script>
Save SrNightmare09/c0492a8852eb172ebea6c93837837998 to your computer and use it in GitHub Desktop.
Download ZIP
Using the CoinMarketCap API: A Beginner's Guide
Raw
coinmarketcap-api.md
Using the CoinMarketCap API: A Beginner's Guide
CoinMarketCap is the world's most-referenced price-tracking website for crypto assets in the rapidly growing cryptocurrency space. Its mission is to make crypto discoverable and efficient globally by empowering retail users with unbiased, high quality and accurate information
In this guide, we will break down the process of leveraging the CoinMarketCap API to seamlessly integrate real-time crptocurrency data in your applications or projects.
While the examples in this blog primarily utilize Python code, it's important to note that the API can be utilized with various programming languages. To explore further, click here.
Getting Started
This section covers the basics of using the CoinMarketCap API to retrieve cryptocurrency data
1. Signing Up to CoinMarketCap
Our first step will be to make an account on CoinMarketCap.
2. Getting your API Key
After creating your account, you will be redirected to your dashboard. If that does not happen, follow this link. From the dashboard, copy your API key and paste it in a local .txt file.
3. Retrieving Crypto Data
Let us write the code that retrieves cryptocurrency data in JSON format. Simply copy and paste the following code into your preferred development environment.
Note: Replace YOUR_API_KEY with the API key you pasted in the .txt file.
View Code
from requests import Session
import json
import pprint
def getInfo (): # Function to get the info
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest' # Coinmarketcap API url
api = 'YOUR_API_KEY' # Replace this with your API key
parameters = { 'slug': 'bitcoin', 'convert': 'USD' } # API parameters to pass in for retrieving specific cryptocurrency data
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api
} # Headers for the API request
session = Session() # Create new session object to manage API requests
session.headers.update(headers) #Update the session headers with the specified headers
response = session.get(url, params=parameters) # Receiving the response from the API
info = json.loads(response.text)
pprint.pprint(info) # Displaying JSON data in a visually pleasing format on the terminal for improved readability
getInfo() # Calling the function to get the data
4. Running the Code
Running this code will produce results such as the following:
View Result
{'data': {'1': {'circulating_supply': 19405368,
'cmc_rank': 1,
'date_added': '2010-07-13T00:00:00.000Z',
'id': 1,
'infinite_supply': False,
'is_active': 1,
'is_fiat': 0,
'last_updated': '2023-06-18T09:00:00.000Z',
'max_supply': 21000000,
'name': 'Bitcoin',
'num_market_pairs': 10247,
'platform': None,
'quote': {'USD': {'fully_diluted_market_cap': 556544808013.3,
'last_updated': '2023-06-18T09:00:00.000Z',
'market_cap': 514283657523.2155,
'market_cap_dominance': 48.0966,
'percent_change_1h': -0.29553396,
'percent_change_24h': -0.30944941,
'percent_change_30d': -1.46162201,
'percent_change_60d': -9.16801758,
'percent_change_7d': 2.92720074,
'percent_change_90d': -6.68909286,
'price': 26502.13371491927,
'tvl': None,
'volume_24h': 9276792871.439861,
'volume_change_24h': -47.1715}},
'self_reported_circulating_supply': None,
'self_reported_market_cap': None,
'slug': 'bitcoin',
'symbol': 'BTC',
'tags': ['mineable',
'pow',
'sha-256',
'store-of-value',
'state-channel',
'coinbase-ventures-portfolio',
'three-arrows-capital-portfolio',
'polychain-capital-portfolio',
'binance-labs-portfolio',
'blockchain-capital-portfolio',
'boostvc-portfolio',
'cms-holdings-portfolio',
'dcg-portfolio',
'dragonfly-capital-portfolio',
'electric-capital-portfolio',
'fabric-ventures-portfolio',
'framework-ventures-portfolio',
'galaxy-digital-portfolio',
'huobi-capital-portfolio',
'alameda-research-portfolio',
'a16z-portfolio',
'1confirmation-portfolio',
'winklevoss-capital-portfolio',
'usv-portfolio',
'placeholder-ventures-portfolio',
'pantera-capital-portfolio',
'multicoin-capital-portfolio',
'paradigm-portfolio',
'bitcoin-ecosystem'],
'total_supply': 19405368,
'tvl_ratio': None}},
'status': {'credit_count': 1,
'elapsed': 35,
'error_code': 0,
'error_message': None,
'notice': None,
'timestamp': '2023-06-18T09:02:13.424Z'}}
Congratulations! If you've found the information you need on using the CoinMarketCap API for cryptocurrency data, you can stop here. But if you want to improve your code for more specific results, keep reading.
Working with the data
You have the flexibility to narrow down the received data and obtain more specific information, such as the price, market cap, and more.
To narrow down the data, it's a straightforward process of adding the corresponding parent elements before each desired data type. For instance, if you want to retrieve the price of Bitcoin, you can achieve that by modifying the following line of code.
# info = json.loads(response.text)
info = json.loads(response.text)['data']['1']['quote']['USD']['price'] # Get only the price of BTC
# OUTPUT : 26510.569334993506
View explaination
Similarly, to retrieve only the symbol of Bitcoin, the line of code will be modified as follows.
# info = json.loads(response.text)
# info = json.loads(response.text)['data']['1']['quote']['USD']['price']
info = json.loads(response.text)['data']['1']['symbol']
# OUTPUT : 'BTC'
Changing Currency
Say we're interested in obtaining the price of Ethereum in Indian Rupee, you can achieve this by adjusting the parameters within the code.
# parameters = { 'slug': 'bitcoin', 'convert': 'USD' }
parameters = { 'slug': 'ethereum', 'convert': 'INR' }
# OUTPUT : 141925.7369671622
Note: Ensure that you update relevant information, such as the ID within the info variable, as you retrieve data for different cryptocurrencies. To locate the ID of a specific cryptocurrency, print its raw data and locate the corresponding ID within the JSON structure.
Conclusion
Congratulations! You have reached the end of this beginner's guide on using the CoinMarketCap API to retrieve cryptocurrency data. We have covered the basics of leveraging the API, from signing up to obtaining your API key and retrieving crypto data in JSON format. If you wish to research the API further, make sure to read the CoinMarketCap Documentation. By following the provided examples and code snippets, you can effortlessly incorporate live cryptocurrency data into your applications or projects. Happy Coding!
Copy link
Cralins
commented
Dec 19, 2022
•
edited
``Thank your code and explanation which i kooking for. Coinmarketcap didnt define so well the argument.
İ made some changes and get AI help to fix my usage. i didnt fulu know github as newbie Can you add this part who ever need.
i am try get historical BTC Closing price data from 2017 to 2023 for data anlysis
Thnks
import configparser
import json
import pytz
from datetime import datetime
from requests import Request, Session
from dateutil import parser
def get_info():
# Read the API key from the coinmarket.ini file
config = configparser.ConfigParser()
config.read('coinmarket.ini')
api_key = config['DEFAULT']['API_KEY']
# Set up the request parameters and headers
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
parameters = { 'slug': 'bitcoin', 'convert': 'USD' }
headers = {
'Accepts': 'application/json',
'X-CMC_PRO_API_KEY': api_key
}
# Send the request and retrieve the response
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
info = json.loads(response.text)
# Extract the desired information from the response
data = info['data']['1']
name = data['name']
symbol = data['symbol']
rank = data['cmc_rank']
total_supply = data['total_supply']
circulating_supply = data['circulating_supply']
market_cap = data['quote']['USD']['market_cap']
price = data['quote']['USD']['price']
market_cap_dominance = data['quote']['USD']['market_cap_dominance']
percent_change_1h = data['quote']['USD']['percent_change_1h']
percent_change_24h = data['quote']['USD']['percent_change_24h']
volume_24h = data['quote']['USD']['volume_24h']
volume_change_24h = data['quote']['USD']['volume_change_24h']
timestamp = info['status']['timestamp']
# Convert the timestamp to a timezone-aware datetime object
timestamp_local = parser.parse(timestamp).astimezone(pytz.timezone('Turkey'))
# Format the timestamp as desired
formatted_timestamp = timestamp_local.strftime('%Y-%m-%d %H:%M:%S')
# Print the information
print(f'Name: {name}, Symbol: {symbol}, Price: {price:,.2f}, Percent change (1h): {percent_change_1h}, Percent change (24h): {percent_change_24h}, Total supply: {total_supply}, Circulating supply: {circulating_supply}, Market capitalization: {market_cap}, Market capitalization dominance: {market_cap_dominance}, Volume (24h): {volume_24h}, Volume change (24h): {volume_change_24h}, Timestamp: {formatted_timestamp}')
get_info()
Sorry, something went wrong.
Copy link
Author
SrNightmare09
commented
Jun 18, 2023
@Cralins I have updated the gist again to make it more concise! Please consider rerunning the code to see view any further problems! If you have any suggestions/feedback please do comment!
Sorry, something went wrong.
Copy link
Rahul-Prasad-07
commented
Sep 6, 2023
hey can you help me with converting crypto price in other currency in express-node.js server
Sorry, something went wrong.
Copy link
CoCo-27
commented
Mar 12, 2024
How can I get hot-pair information from CMC using its API & free API key?
Sorry, something went wrong.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Footer
© 2024 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Docs
Contact
Manage cookies
Do not share my personal information
You can’t perform that action at this time.
CoinMarketCap API Python Tutorial (2024) - Analyzing Alpha
Skip to content
Analyzing Alpha
Analyzing Alpha
Menu
Home
About
Blog
Podcast
Recommended
Menu
Home
About
Blog
Podcast
Recommended
Trading » Trading Systems » Data » APIs
CoinMarketCap API Python Tutorial (2024)
By Leo Smigel
Updated on October 13, 2023
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:
It has a free plan.Easy to use interface.Tracks a large number of crypto assets and exchanges.You can earn crypto while learning using the learn-to-earn plan.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.
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.
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.
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.
Simple Example Fetching Data using CoinMarketCap API in Python
There are two ways to make API calls to the CoinMarketCap API:
Using the python-coinmarketcap libraryUsing 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:
Import the coinmarketcapapi module into your Python application.Create an object of the CoinMarketCapAPI class and pass it your API key.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:
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:
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:
Cryptocurrency Exchange Global MetricsToolsBlockchainFiatPartnersKey
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.
MapInfoLatest Market QuotesLatest Market ListingsCryptocurrency 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:
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:
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:
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:
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:
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:
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:
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:
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 Planexchange_map()/exchange/mapReturns a list of all active cryptocurrencies, including their CoinMarketCap IdsBasicexchange_info()/exchange/infoReturns static metadata for one or more exchanges at CoinMarketCapBasicexchange_listings_latest()/exchange/listings/latestReturns latest listings for all cryptocurrency exchanges at CoinMarketCapStandardexchange_listings_historical()/exchange/listings/historicalReturns historical listings for an exchange based on time and interval parameters Standardexchange_quotes_latest()/exchange/quotes/latestReturns aggregate of latest market data for one or more exchangesStandardexchange_quotes_historical()/exchange/quotes/historicalReturns historical quotes for an exchange based on time and interval parameters Standardexchange_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:
Latest Global MetricsHistorical 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:
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:
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:
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:
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:
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:
Pandas gspreaddf2gspread
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 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:
LiquidityTrading inefficiencies across exchangesAverage 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 Cancel replyCommentName
Save my name, email, and website in this browser for the next time I comment.
Δ
Subscribe to the Newsletter
Join 1300+ traders and investors discovering the secrets of legendary market wizards in a free weekly email.
Share this Article
XLinkedInFacebookEmail
Get Exclusive Tips
Sign up for the newsletter to get tips and strategies I don't share anywhere else.
Analyzing Alpha2009 Mackenzie WaySuite 100Cranberry Twp, PA 16066P: 412-212-3240E: info [ at ] analyzingalpha.com
© Analyzing Alpha
Contact
Privacy
DCMA
Terms
Disclosure
Disclaimer
Sitemap
Analyzing Alpha is reader-supported. We may earn an affiliate commission when you buy through links on our site. As an Amazon Associate, we earn from qualifying purchases.
CoinMarketCap API Python Tutorial (2024) - Analyzing Alpha
Skip to content
Analyzing Alpha
Analyzing Alpha
Menu
Home
About
Blog
Podcast
Recommended
Menu
Home
About
Blog
Podcast
Recommended
Trading » Trading Systems » Data » APIs
CoinMarketCap API Python Tutorial (2024)
By Leo Smigel
Updated on October 13, 2023
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:
It has a free plan.Easy to use interface.Tracks a large number of crypto assets and exchanges.You can earn crypto while learning using the learn-to-earn plan.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.
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.
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.
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.
Simple Example Fetching Data using CoinMarketCap API in Python
There are two ways to make API calls to the CoinMarketCap API:
Using the python-coinmarketcap libraryUsing 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:
Import the coinmarketcapapi module into your Python application.Create an object of the CoinMarketCapAPI class and pass it your API key.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:
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:
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:
Cryptocurrency Exchange Global MetricsToolsBlockchainFiatPartnersKey
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.
MapInfoLatest Market QuotesLatest Market ListingsCryptocurrency 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:
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:
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:
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:
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:
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:
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:
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:
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 Planexchange_map()/exchange/mapReturns a list of all active cryptocurrencies, including their CoinMarketCap IdsBasicexchange_info()/exchange/infoReturns static metadata for one or more exchanges at CoinMarketCapBasicexchange_listings_latest()/exchange/listings/latestReturns latest listings for all cryptocurrency exchanges at CoinMarketCapStandardexchange_listings_historical()/exchange/listings/historicalReturns historical listings for an exchange based on time and interval parameters Standardexchange_quotes_latest()/exchange/quotes/latestReturns aggregate of latest market data for one or more exchangesStandardexchange_quotes_historical()/exchange/quotes/historicalReturns historical quotes for an exchange based on time and interval parameters Standardexchange_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:
Latest Global MetricsHistorical 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:
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:
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:
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:
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:
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:
Pandas gspreaddf2gspread
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 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:
LiquidityTrading inefficiencies across exchangesAverage 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 Cancel replyCommentName
Save my name, email, and website in this browser for the next time I comment.
Δ
Subscribe to the Newsletter
Join 1300+ traders and investors discovering the secrets of legendary market wizards in a free weekly email.
Share this Article
XLinkedInFacebookEmail
Get Exclusive Tips
Sign up for the newsletter to get tips and strategies I don't share anywhere else.
Analyzing Alpha2009 Mackenzie WaySuite 100Cranberry Twp, PA 16066P: 412-212-3240E: info [ at ] analyzingalpha.com
© Analyzing Alpha
Contact
Privacy
DCMA
Terms
Disclosure
Disclaimer
Sitemap
Analyzing Alpha is reader-supported. We may earn an affiliate commission when you buy through links on our site. As an Amazon Associate, we earn from qualifying purchases.
CoinMarketCap API Python Tutorial (2024) - Analyzing Alpha
Skip to content
Analyzing Alpha
Analyzing Alpha
Menu
Home
About
Blog
Podcast
Recommended
Menu
Home
About
Blog
Podcast
Recommended
Trading » Trading Systems » Data » APIs
CoinMarketCap API Python Tutorial (2024)
By Leo Smigel
Updated on October 13, 2023
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:
It has a free plan.Easy to use interface.Tracks a large number of crypto assets and exchanges.You can earn crypto while learning using the learn-to-earn plan.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.
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.
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.
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.
Simple Example Fetching Data using CoinMarketCap API in Python
There are two ways to make API calls to the CoinMarketCap API:
Using the python-coinmarketcap libraryUsing 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:
Import the coinmarketcapapi module into your Python application.Create an object of the CoinMarketCapAPI class and pass it your API key.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:
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:
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:
Cryptocurrency Exchange Global MetricsToolsBlockchainFiatPartnersKey
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.
MapInfoLatest Market QuotesLatest Market ListingsCryptocurrency 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:
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:
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:
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:
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:
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:
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:
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:
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 Planexchange_map()/exchange/mapReturns a list of all active cryptocurrencies, including their CoinMarketCap IdsBasicexchange_info()/exchange/infoReturns static metadata for one or more exchanges at CoinMarketCapBasicexchange_listings_latest()/exchange/listings/latestReturns latest listings for all cryptocurrency exchanges at CoinMarketCapStandardexchange_listings_historical()/exchange/listings/historicalReturns historical listings for an exchange based on time and interval parameters Standardexchange_quotes_latest()/exchange/quotes/latestReturns aggregate of latest market data for one or more exchangesStandardexchange_quotes_historical()/exchange/quotes/historicalReturns historical quotes for an exchange based on time and interval parameters Standardexchange_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:
Latest Global MetricsHistorical 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:
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:
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:
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:
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:
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:
Pandas gspreaddf2gspread
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 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:
LiquidityTrading inefficiencies across exchangesAverage 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 Cancel replyCommentName
Save my name, email, and website in this browser for the next time I comment.
Δ
Subscribe to the Newsletter
Join 1300+ traders and investors discovering the secrets of legendary market wizards in a free weekly email.
Share this Article
XLinkedInFacebookEmail
Get Exclusive Tips
Sign up for the newsletter to get tips and strategies I don't share anywhere else.
Analyzing Alpha2009 Mackenzie WaySuite 100Cranberry Twp, PA 16066P: 412-212-3240E: info [ at ] analyzingalpha.com
© Analyzing Alpha
Contact
Privacy
DCMA
Terms
Disclosure
Disclaimer
Sitemap
Analyzing Alpha is reader-supported. We may earn an affiliate commission when you buy through links on our site. As an Amazon Associate, we earn from qualifying purchases.
CoinMarketCap API Python Tutorial (2024) - Analyzing Alpha
Skip to content
Analyzing Alpha
Analyzing Alpha
Menu
Home
About
Blog
Podcast
Recommended
Menu
Home
About
Blog
Podcast
Recommended
Trading » Trading Systems » Data » APIs
CoinMarketCap API Python Tutorial (2024)
By Leo Smigel
Updated on October 13, 2023
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:
It has a free plan.Easy to use interface.Tracks a large number of crypto assets and exchanges.You can earn crypto while learning using the learn-to-earn plan.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.
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.
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.
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.
Simple Example Fetching Data using CoinMarketCap API in Python
There are two ways to make API calls to the CoinMarketCap API:
Using the python-coinmarketcap libraryUsing 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:
Import the coinmarketcapapi module into your Python application.Create an object of the CoinMarketCapAPI class and pass it your API key.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:
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:
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:
Cryptocurrency Exchange Global MetricsToolsBlockchainFiatPartnersKey
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.
MapInfoLatest Market QuotesLatest Market ListingsCryptocurrency 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:
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:
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:
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:
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:
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:
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:
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:
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 Planexchange_map()/exchange/mapReturns a list of all active cryptocurrencies, including their CoinMarketCap IdsBasicexchange_info()/exchange/infoReturns static metadata for one or more exchanges at CoinMarketCapBasicexchange_listings_latest()/exchange/listings/latestReturns latest listings for all cryptocurrency exchanges at CoinMarketCapStandardexchange_listings_historical()/exchange/listings/historicalReturns historical listings for an exchange based on time and interval parameters Standardexchange_quotes_latest()/exchange/quotes/latestReturns aggregate of latest market data for one or more exchangesStandardexchange_quotes_historical()/exchange/quotes/historicalReturns historical quotes for an exchange based on time and interval parameters Standardexchange_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:
Latest Global MetricsHistorical 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:
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:
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:
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:
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:
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:
Pandas gspreaddf2gspread
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 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:
LiquidityTrading inefficiencies across exchangesAverage 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 Cancel replyCommentName
Save my name, email, and website in this browser for the next time I comment.
Δ
Subscribe to the Newsletter
Join 1300+ traders and investors discovering the secrets of legendary market wizards in a free weekly email.
Share this Article
XLinkedInFacebookEmail
Get Exclusive Tips
Sign up for the newsletter to get tips and strategies I don't share anywhere else.
Analyzing Alpha2009 Mackenzie WaySuite 100Cranberry Twp, PA 16066P: 412-212-3240E: info [ at ] analyzingalpha.com
© Analyzing Alpha
Contact
Privacy
DCMA
Terms
Disclosure
Disclaimer
Sitemap
Analyzing Alpha is reader-supported. We may earn an affiliate commission when you buy through links on our site. As an Amazon Associate, we earn from qualifying purchases.