如何修改CoinBase API调用函数以正常获取产品Ticker数据?
解决CoinBase API获取产品Ticker数据的错误问题
错误原因分析
第一个函数返回
{"message": "NotFound"}:- 大概率是传入的
product_id格式错误,CoinBase Exchange的产品ID必须是交易对格式(如BTC-USD、ETH-EUR),需严格匹配平台支持的产品; - 同时请求缺少
User-Agent头,CoinBase API强制要求该字段,缺失可能导致请求被拦截或识别异常。
- 大概率是传入的
第二个函数返回
{"message":"User-Agent header is required."}:- 请求头中未包含
User-Agent字段,这是CoinBase API的强制要求。
- 请求头中未包含
修改后的第一个函数(推荐使用requests库)
直接给修改后的代码,添加必要的请求头并确保product_id正确:
import requests import json def connect_to_coinbase_ticker(product_id: str): # 确保product_id是正确的交易对格式,比如"BTC-USD" url = f"https://api.exchange.coinbase.com/products/{product_id}/ticker" # 添加User-Agent头,同时保留accept字段 headers = { "accept": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36" } try: response = requests.get(url, headers=headers) # 先检查响应状态码 response.raise_for_status() ticker_data = response.json() print(json.dumps(ticker_data, indent=4)) return ticker_data except requests.exceptions.RequestException as e: print(f"请求出错: {e}") print(f"响应内容: {response.text}")
修改说明
- 添加User-Agent头:随便填一个合法的User-Agent值即可,比如浏览器标识,满足API的强制要求;
- 状态码检查:通过
raise_for_status()捕获HTTP错误(比如404、403),方便排查问题; - 异常处理:捕获请求过程中的网络错误,避免程序直接崩溃;
- product_id验证:调用函数时必须传入正确的交易对ID,比如
connect_to_coinbase_ticker("BTC-USD")。
若修改第二个函数(http.client版本)
只需在headers中添加User-Agent字段即可:
import http.client def connect_to_coinbase_ticker(product_id: str): conn = http.client.HTTPSConnection("api.exchange.coinbase.com") payload = '' headers = { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } conn.request("GET", f"/products/{product_id}/ticker", payload, headers) res = conn.getresponse() data = res.read() print(data.decode("utf-8"))
内容的提问来源于stack exchange,提问作者useeeeer132
相关产品推荐
相关产品推荐

