Tambot
Tambot

Reputation: 1

Coinmarketcap API to Google Sheets / Google Scripts Get Live coin price

Hi I'm trying to get the price of specific Crypto coins to add to a google sheets. I've managed to get this google script working when I hard code the value of "symbol" however I'm trying to pass the coin I'm trying to price out and I think I'm running to a simple syntax issue but I can't figure it out. I think I need to escape the "ticker" value but I can't seem to figure out how.

This works if I hardcode ticker value to "BTC"

function getCPrice(ticker) {
  var url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest";
  var apiKey = 'replaced-my-api-key'; // Replace with your API key
    var headers = {
    "X-CMC_PRO_API_KEY": apiKey,
    "Accept": "application/json"
  };

  var parameters = {
    "symbol": ticker  // **think the issue is here** or works with "BTC"
  };

var response = UrlFetchApp.fetch(url + "?" + Object.keys(parameters).map(key => key + '=' + parameters[key]).join('&'), {'headers': headers});
var json = JSON.parse(response.getContentText());
var cPrice = json.data[ticker].quote.USD.price;  // works with json.data.BTC.quote.USD.Price

return cPrice;
}

Any help would be appreciated,

Thanks in advance,

AT

I was expecting the ticker value passed in to pull the correct crypto price after parsing however I get this error:

Error Exception: Request failed for https://pro-api.coinmarketcap.com returned code 400. Truncated server response: {"status":{"timestamp":"2024-05-16T07:53:46.738Z","error_code":400,"error_message":""symbol" is not allowed to be empty","elapsed":0,"credit_coun... (use muteHttpExceptions option to examine full response) (line 56).

Upvotes: 0

Views: 146

Answers (0)

Related Questions