-1

TL;DR

How to run report on GA4 property in GAS? Do I use AnalyticsData namespace or Analytics? or am I doing something wrong with properties?!

      report = AnalyticsAdmin.Properties.runReport(request,
        'properties/' + 'zxc');

      Logger.log('We dont get here ' + report);

I've seen this oldish question (similar to this question) but can't seem to use that: enter image description here

Objective

The script is designed to automate the process of retrieving visitor count data from Google Analytics on a weekly basis and updating a Google Sheet with the results. The main steps include:

  1. Identifying the Google Analytics Account and Property: The script finds the relevant Google Analytics account and property (specifically the 'new' GA4 properties) by matching the account name and id from a Google Sheet.
  2. Listing Web Data Streams: It lists all web data streams (equivalent to views in Universal Analytics) for the identified property.
  3. Running a Report: The script attempts to run a report to retrieve the total visitor count (sessions) for a specified date range, typically the past week.
  4. Updating Google Sheet: The report results are intended to be added to the working sheet in a new column with the date as the header. The total visitors for the week are summed up at the bottom of the rows.

Challenges

The main challenges faced in the script include:

  • Transitioning from the older Google Analytics API to the new Google Analytics Admin API and Data API.
  • Generating the request for the Google Analytics API Executing the report request via Google
  • Analytics API Debugging issues related to permissions and API method calls.

Status

The script is in the development phase, and the current focus is on resolving the error encountered while running the report to retrieve the visitor count data.

The final implementation will enable automated, weekly updates to the Google Sheet with visitor count data from the selected Google Analytics property, streamlining the reporting process for the organization.

Note: When running this request inthe GA Query Explorer I get a valid Json response:

{
"metricHeaders":[
{
"name":"sessions"
"type":"TYPE_INTEGER"
}
]
"rows":[
{
"metricValues":[...]
}
]
"rowCount":1
"metadata":{
"currencyCode":"ZZZ"
"timeZone":"XX/YY"
}
"kind":"analyticsData#runReport"
}
function getReportDataForProperty(view, property) {
  Logger.log(view);
  Logger.log(property);

  // Extract the property ID from the property object
  const matchedViewId = view.name.split('/')[3];
  const matchedPropertyId = property.name.split('/')[1];

  Logger.log(matchedViewId);
  Logger.log(matchedPropertyId);

  try {
      const metrics =  [
        { "name": "sessions" }
        //See avaiable metrics https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema?hl=en#metrics
        ]
      const dateRange = AnalyticsData.newDateRange();
      dateRange.startDate = getLastNdays(7);
      dateRange.endDate = 'today';

      const request = AnalyticsReporting.newReportRequest();
      request.metrics = metrics;
      request.dateRanges = dateRange;
      //request.property = "properties/zxc";

      Logger.log(request);

      // --------------------- SUPPORT NEEDED HERE ---------------------

      report = AnalyticsAdmin.Properties.runReport(request,
        'properties/' + 'zxc');

      // I also tried report = AnalyticsData.Properties.runReport(request,
        'properties/' + 'zxc');

      // I also tried 
      // request.property = 'properties/ + propertyId'
      // report = AnalyticsAdmin.Properties.runReport(request);

      Logger.log('We dont get here ' + report);
      
      // --------------------- SUPPORT NEEDED HERE ---------------------
      if (!report.rows) {
        Logger.log('No rows returned.');
        return;
      }
  } catch (e) {
    Logger.log(e)
    // TODO (Developer) - Handle exception
    Logger.log('Failed with error: %s', e.error);
  }
}

// EDIT: I've had run the Google example before posting, but not shared details about this. I'm receiving the following error when running the code. The only thing I changed was the Property Id. As you can see in the 6 I have added the "AnalyticsData" API namespace to the script.

Execution log
1:29:32 PM  Notice  Execution started
1:29:33 PM  Info    Failed with error: undefined
1:29:32 PM  Notice  Execution completed

Testing Google demo script

RobSteward
  • 305
  • 3
  • 11
  • You are using AnalyticsAdmin you need to use AnalyticsData i beleave. There should be a beta version of it. – Linda Lawton - DaImTo Aug 10 '23 at 09:33
  • Hi @LindaLawton-DaImTo - as I mentioned in the TL;DR and the code snippet, I tried that as well. – RobSteward Aug 10 '23 at 15:35
  • okay but what is the error? – Linda Lawton - DaImTo Aug 10 '23 at 17:42
  • [The sample code of Analytics Data Service](https://developers.google.com/apps-script/advanced/analyticsdata#sample_code) should help you. – idfurw Aug 15 '23 at 08:19
  • Thanks @idfurw, but I've based my code on this example. For me, copying the example and running it does not work. See edit in my original question. – RobSteward Aug 16 '23 at 11:29
  • @LindaLawton-DaImTo Well - multiple depending on what I try. Currently, trying to use `AnalyticsData.newRunReportRequest()` building fails: `1:33:55 PM Info TypeError: AnalyticsData.newRunReportRequest is not a function 1:33:55 PM Info Failed with error: null 1:33:54 PM Notice Execution completed` Note though, that, as I mentioned in my question, I have tried all the NameSpaces, I've tried builting the request in different ways and I also tried running `runReport()` with static json request parameter instead of building the request object first. – RobSteward Aug 16 '23 at 11:35

1 Answers1

1

First I would start with removing all of those other serives. you have data, admin and reporting included.

Then just enable data api.

You need to make sure that you have enabled the service

enter image description here

Make sure the analytics data is listed.

enter image description here

code

/**
 * Runs a report of a Google Analytics 4 property ID. Creates a sheet with the
 * report.
 */
function runReport() {
  /**
   * TODO(developer): Uncomment this variable and replace with your
   *   Google Analytics 4 property ID before running the sample.
   */
  const propertyId = '250796939';  

  try {
    const metric = AnalyticsData.newMetric();    
    metric.name = 'activeUsers';

    const dimension = AnalyticsData.newDimension();
    dimension.name = 'city';

    const dateRange = AnalyticsData.newDateRange();
    dateRange.startDate = '2020-03-31';
    dateRange.endDate = 'today';

    const request = AnalyticsData.newRunReportRequest();
    request.dimensions = [dimension];
    request.metrics = [metric];
    request.dateRanges = dateRange;

    const report = AnalyticsData.Properties.runReport(request,
        'properties/' + propertyId);
    if (!report.rows) {
      console.log('No rows returned.');
      return;
    }


  } catch (e) {
    // TODO (Developer) - Handle exception
    console.log('Failed with error: %s', e.error);
  }
}
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • I'm not really sure why, but the removal of the two other identifiers resolved this. In my opinion they this should not have helped, as the identifier clearly labels, which API I would want to call. But it did. So thanks Linda! If you can explain the logic here, that would be amazing. – RobSteward Aug 16 '23 at 18:18
  • I dont know either but When i was testing your code i hit the same issue and i was wondering they were bashing or something. Im going to see if i cant recreate it and let the team know. – Linda Lawton - DaImTo Aug 17 '23 at 06:43