【GAS】Retrieving Data from Google Analytics GA4


Creating a GAS Script to Retrieve Data from Google Analytics GA4

Preparation

Adding Google Analytics Data API

Certainly

Please make sure to check the GA4 account ID in advance.

function runReport() {
  const propertyId = '<GA4 Account ID>';

  try {
    // Set up metrics (e.g., activeUsers and eventCount)
    const metric = {
      name: 'activeUsers'
    };

    const metric1 = {
      name: 'eventCount'
    };

    // Set up dimensions (e.g., date and eventName)
    const dimension = {
      name: 'date'
    };

    const dimension1 = {
      name: 'eventName'
    };

    // Set up date range
    const dateRange = {
      startDate: '7daysAgo',
      endDate: 'yesterday'
    };

    const request = {
      entity: {
        propertyId: propertyId
      },
      dimensions: [dimension, dimension1],
      metrics: [metric, metric1],
      dateRanges: [dateRange]
    };

    const response = Analytics.Data.ga.get(request);

    if (!response.rows) {
      Logger.log('No rows returned.');
      return;
    }

    const headers = [...response.columnHeaders.map(header => header.name)];
    const rows = [headers, ...response.rows];
    return rows;
  } catch (e) {
    // TODO (Developer) - Handle exception
    Logger.log('Failed with error: %s', e.error);
  }
}

function getDate() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName("Sheet1");
  const rows = runReport();
  sh.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
}

https://developers.google.com/apps-script/advanced/analyticsdata

Commonly Used Metrics and Dimensions

dateRange

today
yesterday
7daysAgo7 days ago
28daysAgo28 days ago
2020-09-01 Specific date: [Insert specific date]

Metrics

activeUsersThe number of distinct users who visited your site or app.
eventCountThe count of events.
conversionsIs conversion event
newUsersThe number of users who interacted with your site or launched your app for the first time (event triggered: first_open or first_visit).
userEngagementDurationThe total amount of time (in seconds) your website or app was in the foreground of users’ devices.

Dimensions

cityThe city from which the user activity originated.
countryThe country from which the user activity originated.
dateThe date of the event, formatted as YYYYMMDD.
dateHourThe combined values of date and hour formatted as YYYYMMDDHH.
dayThe day of the month, a two-digit number from 01 to 31.
dayOfWeekThe integer day of the week. It returns values in the range [0,6] with Sunday as the first day of the week.
fullPageUrlThe hostname, page path, and query string for web pages visited; for example, the fullPageUrl portion of https://www.example.com/store/contact-us?query_string=true is www.example.com/store/contact-us?query_string=true.
googleAdsAccountNameThe Account name from Google Ads for the campaign that led to the conversion event. Corresponds to customer.descriptive_name in the Google Ads API.
landingPageThe page path associated with the first pageview in a session.
operatingSystemThe operating systems used by visitors to your app or website. Includes desktop and mobile operating systems such as Windows and Android.
pageReferrerThe full referring URL including the hostname and path. This referring URL is the user’s previous URL and can be this website’s domain or other domains. Populated by the event parameter 'page_referrer’.

https://developers.google.com/analytics/devguides/reporting/data/v1?hl=ja

https://developers.google.com/analytics/devguides/reporting/data/v1/api-schema