How to Use Bitquery APIs in Google Apps Script

In this tutorial, we will see how to run a script on Google Apps Script, which is a lightweight tool to run scripts. When it comes to building dApps on blockchain data, Google Apps Script with Bitquery APIs can be a powerful stack.

Step-by-Step Tutorial

Create an API key for Bitquery.io. You can do this by going to the Bitquery.io website and signing up for a free developer account.

Create an empty script Code.gs file in Google Apps Script

We will create a variable to store the API KEY from Bitquery.

const API_KEY = "your key";

The query variable contains the GraphQL query that will be sent to the Bitquery.io API. The one written below gets the latest 10 trades for the pair USDT/ RWT .

let query = `{
  ethereum(network: bsc) {
    dexTrades(
      options: {desc: ["block.height", "tradeIndex"], limit: 10}
      baseCurrency: {is: "0x55d398326f99059ff775485246999027b3197955"}
      quoteCurrency: {is: "0xec1f55b5be7ee8c24ee26b6cc931ce4d7fd5955c"}
      date: {after: "2023-04-28"}
    ) {
      transaction {
        hash
      }
      tradeIndex
      smartContract {
        address {
          address
        }
        contractType
        currency {
          name
        }
      }
      tradeIndex
      date {
        date
      }
      block {
        height
      }
      buyAmount
      buyAmountInUsd: buyAmount(in: USD)
      buyCurrency {
        symbol
        address
      }
      sellAmount
      sellAmountInUsd: sellAmount(in: USD)
      sellCurrency {
        symbol
        address
      }
      sellAmountInUsd: sellAmount(in: USD)
      tradeAmount(in: USD)
      transaction {
        gasValue
        gasPrice
        gas
      }
    }
  }
}
`;

The opts variable contains the HTTP request options. This includes the Content-Type header, which specifies that the request body is JSON, and the X-API-KEY header, which contains the API key.

let opts = {
    method: "post",
    muteHttpExceptions:true,
    headers: {
      "Content-Type": "application/json",
      "X-API-KEY": API_KEY,
    },
    payload: JSON.stringify({
      "query":query  
      ,"variables" : "{}"
  })
  };

The response variable stores the response from the Bitquery.io API. The text variable stores the text content of the response.

Next we write a Logger.log() function to log messages to the console.


Logger.log(opts);
  let response = UrlFetchApp.fetch("https://graphql.bitquery.io", opts);
  Logger.log(response);

  if (response === null) {
    // Handle the error appropriately.
    console.log(response)
    
  } else {
    let text = response.getContentText();

    // Do something with the text content of the response.
  }

This is a basic guide to run a script. You can write complex queries and perform other functions with the retrieved data.