miguel
miguel

Reputation: 1

coinmarketcap API // json

i try to read crypto prices into google sheets via cmc api.

i got this function via app script

function getCryptoData(x) {
  var url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?convert=EUR";
  var apiKey = 'xyz'; // Replace with your API key
  var headers = {
    "X-CMC_PRO_API_KEY": apiKey,
    "Accept": "application/json"
  };

  var response = UrlFetchApp.fetch(url, {'headers': headers});
  var json = JSON.parse(response.getContentText());
  return json.data[x].quote.EUR.price; // Example: Fetches the price of the x-th listed cryptocurrency in EUR
}

now i don't want the price of the x-th data entry of the json, i want the price of the currency where id = x. i think this is a json dictionary, however i am not able to get it right. as an example, the id for BTC = 1, the id for ETH = 1027.

this is a basic question, i am new to this, so please bear with me. is this understandable?

i tried to run through the dictionary with for and if, to no avail.

for id in data['id']
  if id == x
    return json.data[].quote.EUR.price;

so, i don't know how to reference the right dictionary entry.

this is the complete output of the json of this url, as i understand it: https://docs.google.com/spreadsheets/d/1h9PmgIJWt0L5cD2pYRLOwEKhUi-K_OFY-C-n6vQEAcY/edit?usp=sharing

Upvotes: -2

Views: 130

Answers (1)

Lime Husky
Lime Husky

Reputation: 775

Getting Specific Crypto Prices using CMC API

I tried your code and it seems to be missing a function and it also has an error. I modified and converted your python into Javascript and added the forEach() function to iterate each data if the ID is matched in your array it will return the CRYPTO value as EURO as to match in your script json.data[x].quote.EUR.price.

Code.gs

function getCryptoData(id) {
  var url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?convert=EUR";
  var apiKey = 'xyz'; // Replace with your API key
  var headers = {
    "X-CMC_PRO_API_KEY": apiKey,
    "Accept": "application/json"
  };

  var response = UrlFetchApp.fetch(url, { 'headers': headers });
  var json = JSON.parse(response.getContentText());
  json.data.forEach(x => {
    if (x.id == id) {
      console.log(x.name, x.quote.EUR.price)
      return x.quote.EUR.price
    }
  })
}

Sample Output:

Sample 1 Sample 2

Reference:

Upvotes: 0

Related Questions