如何使用PHP从CoinMarketCap API获取比特币价格
Hey there! Let's break down how you can pull Bitcoin's price from that CoinMarketCap API to build your BTC buying app. I'll walk you through the key parts and share some example code to get you started.
The endpoint you're targeting is https://api.coinmarketcap.com/v2/ticker/1/ — the 1 here corresponds to Bitcoin's unique ID on CoinMarketCap, so this will only return data for BTC, which is exactly what you need.
When you hit that endpoint, you'll get a JSON response structured like this (I've cleaned it up a bit for readability):
{ "data": { "id": 1, "name": "Bitcoin", "symbol": "BTC", "website_slug": "bitcoin", "rank": 1, "circulating_supply": 17039387.0, "total_supply": 17039387.0, "max_supply": 21000000.0, "quotes": { "USD": { "price": 8220.55, "volume_24h": 5658720000.0, "market_cap": 140073132803.0, "percent_change_1h": 0.28, "percent_change_24h": -1.18, "percent_change_7d": -10.28 } }, "last_updated": 1526587771 }, "metadata": { "timestamp": 1526587666, "error": null } }
The value you care most about is the BTC price in USD, which lives at the path data.quotes.USD.price. That's the number you'll want to pull into your app for pricing calculations.
Let's look at quick examples in two common languages for app development:
Python (using requests library)
First, make sure you have the requests package installed (pip install requests), then use this code:
import requests def get_btc_price(): url = "https://api.coinmarketcap.com/v2/ticker/1/" response = requests.get(url) if response.status_code == 200: data = response.json() return data['data']['quotes']['USD']['price'] else: print(f"Error fetching data: {response.status_code}") return None # Usage btc_price = get_btc_price() if btc_price: print(f"Current BTC price: ${btc_price:.2f}")
JavaScript (browser-side fetch)
If you're building a web app, you can use the browser's built-in fetch API:
async function getBtcPrice() { try { const response = await fetch("https://api.coinmarketcap.com/v2/ticker/1/"); const data = await response.json(); const btcPrice = data.data.quotes.USD.price; console.log(`Current BTC price: $${btcPrice.toFixed(2)}`); return btcPrice; } catch (error) { console.error("Error fetching BTC price:", error); return null; } } // Call the function getBtcPrice();
- Error Handling: Always add checks for failed requests (like the examples above) — API calls can fail due to network issues or rate limits.
- Rate Limits: Keep in mind CoinMarketCap's rate limits for their free API to avoid getting blocked.
- Currency: The example returns USD, but if you need other currencies, you'd have to verify if the API supports multi-currency quotes (this specific endpoint only returns USD by default).
内容的提问来源于stack exchange,提问作者Clarke

