Search code examples
google-apps-scriptgoogle-analyticsgoogle-analytics-apigoogle-analytics-4

GA4 | Google Analytics Admin API | Apps Script


I am trying to call the (new) alpha GA Admin API for the simple task of listing all the Accounts that I have access to... I am at a stage where I call the API but I do not get any error message nor I see the information on the google sheet. Can you please help?

function listGA4Accounts() {
  var sheet = _setupListGA4AccountsSheet();

  var accounts = AnalyticsAdmin.Accounts.list();
  if (accounts.items && accounts.items.length) {
  for (var i = 0; i < accounts.items.length; i++) {
    var account = accounts.items[i];
    var rowNum = i+2;
    sheet.getRange("A" + rowNum).setNumberFormat('@')
         .setValue(account.name).setBackground(AUTO_POP_CELL_COLOR);
    sheet.getRange("B" + rowNum)
         .setValue(account.displayName).setBackground(AUTO_POP_CELL_COLOR);
    sheet.getRange("C" + rowNum)
         .setValue(account.createTime).setBackground(AUTO_POP_CELL_COLOR);
  }
}
}

The above was adapted from the old code being used for Universal Analytics/GA3 and used to work just fine. What I am missing? I also have a standard GCP project in place and the API is enabled for that GCP project.

Any help/thoughts on the above are highly appreciated.

Thanks.


Solution

  • You have been quite close to the solution.

    TIPS for debugging the API response:

    • prompt the API response in the console with Logger.log(JSON.stringify(<API RESPONSE>))
    • copy the log and paste it on a JSON formatter website like this one: https://jsonformatter.curiousconcept.com/
    • check the actual structure
    • OPTIONAL: copy the formatted JSON from the page & save it in the script as a variable and use this instead of the API response to prepare the code. Once it's working properly with the saved data you can switch back to the data from the API request.

    Following things that I changed:

    1. removed var sheet = _setupListGA4AccountsSheet(); (was not relevant for testing the API response)
    2. just changed the way the JSON object is accessed bc it's a nested one, to get an account item it's necessary to write <variable name>.accounts.item

    Here is the code that can be copied as-is to App Script editor and can be tested:

    function listGA4Accounts() {
      var accounts = AnalyticsAdmin.Accounts.list();
      if (accounts && !accounts.error) {
        accounts = accounts.accounts; // <== this is why it didn't work is a nested JSON
        Logger.log(accounts[0]);
        for (var i = 0, account; account = accounts[i]; i++) {
          Logger.log(account);
    
          /**
           * PLACE your code here
          */
        }
      }
    }