Search code examples
apigoogle-apps-scriptcoinmarketcap

Not able to return price detail in quote using CoinMarketCap api endpoint '/v1/cryptocurrency/quotes/latest' in google appscript


I'm using google appscript to try and retrieve the price details for individual currencies using CoinMarketCap api quotes endpoint as opposed to the listing that fetches 5000 pairs at a time, lest I dry out my api credits for the month in less than a week. But for some reason the quote returned is

quote: { USD: [Object] } }

To give an excerpt of the returned JSON:

{ BTC: 
   { id: 1,
     name: 'Bitcoin',
     symbol: 'BTC',
     slug: 'bitcoin',
     num_market_pairs: 9466,
     date_added: '2013-04-28T00:00:00.000Z',
     tags: 
      [ 'mineable',
        'pow',
        'sha-256',
....
....
     self_reported_circulating_supply: null,
     self_reported_market_cap: null,
     last_updated: '2022-05-27T04:37:00.000Z',
     quote: { USD: [Object] } },

How can I retrieve the actual quote figure for my currency?


Solution

  • Per the API Documentation, the quote structure is:

    "quote": {
      "USD": {
        "price": 6602.60701122,
        "volume_24h": 4314444687.5194,
        "volume_change_24h": -0.152774,
        "percent_change_1h": 0.988615,
        "percent_change_24h": 4.37185,
        "percent_change_7d": -12.1352,
        "percent_change_30d": -12.1352,
        "market_cap": 852164659250.2758,
        "market_cap_dominance": 51,
        "fully_diluted_market_cap": 952835089431.14,
        "last_updated": "2018-08-09T21:56:28.000Z"
      }
    }
    

    A useful method to log objects effectively is:

    Logger.log(JSON.stringify(theObject))
    

    Additionally:

    const key = `...`
    const url = `...`
    const options = {
      method: "GET",
      headers: { 
        "X-CMC_PRO_API_KEY": key 
      },
      json: true,
      gzip: true,
    }
    
    const response = UrlFetchApp.fetch(url, options).getContentText()
    const coinData = Object.entries(JSON.parse(response).data)
    
    for (let [coin, data] of coinData) {
      Logger.log(`${coin}: ${data.quote.USD.price}`)
    } 
    

    By converting the data object into an array, you can iterate/loop the data as shown above.

    Learn More: