fedmar
fedmar

Reputation: 1

CoinMarketCap API / Cannot read properties of undefined 'quote'

I am trying to fetch the last quote data from CoinMarketCap using their API, into a GoogleSheets document to manage my portfolio. I am using Google Apps Script to fetch the data, but I keep getting an “undefined ‘quote’” error.

Error TypeError: Cannot read properties of undefined (reading 'quote') coin_price @ Code.gs:37

Am I missing something in my code? Am I missing something in the API documentation?

Below you will find the function I've been using until today, that I got the error.

Thanks in advance!

CMC API documentation https://coinmarketcap.com/api/documentation/v1/#operation/getV2CryptocurrencyQuotesLatest

function coin_price() {
  const myGoogleSheetName =
    SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Coins");

  const coinMarketCapAPICall = {
    method: "GET",

    uri: "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest",

    qs: {
      start: "1",

      limit: "200",

      convert: "USD",
    },

    headers: { "X-CMC_PRO_API_KEY": "here-I-insert-my-API" },

    json: true,

    gzip: true,
  };

  // Get the coins I want from spreadsheet

  let myCoinSymbols = [];

  const getValues = SpreadsheetApp.getActiveSheet().getDataRange().getValues();

  for (let i = 0; i < getValues.length; i++) {
    // 1 = Column B in the spreadsheet.

    const coinSymbol = getValues[i][1];

    if (coinSymbol) {
      myCoinSymbols.push(coinSymbol);
    }
  }

  for (let i = 0; i < myCoinSymbols.length; i++) {
    const ticker = myCoinSymbols[i];

    const coinMarketCapUrl = `https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=${ticker}`;

    const result = UrlFetchApp.fetch(coinMarketCapUrl, coinMarketCapAPICall);

    const txt = result.getContentText();

    const d = JSON.parse(txt);

    const row = i + 2;

    myGoogleSheetName
      .getRange(row, 12)
      .setValue(d.data[ticker].quote.USD.price);
  }
}

I tried to follow the documentation but couldn't find the source of the error.

Upvotes: 0

Views: 122

Answers (0)

Related Questions