Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created July 16, 2020 02:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/dc3e9c8dfec9403ed0b1935605ea1476 to your computer and use it in GitHub Desktop.
Save tanaikech/dc3e9c8dfec9403ed0b1935605ea1476 to your computer and use it in GitHub Desktop.
Retrieving Users, Sessions and PageViews of User Summary Report from Google Analytics using Google Apps Script

Retrieving Users, Sessions and PageViews of User Summary Report from Google Analytics using Google Apps Script

This is a sample script for retrieving "Users", "Sessions" and "PageViews" of User Summary Report from Google Analytics using Google Apps Script. When you use this, please enable Analytics Reporting API at Advanced Google services.

Sample script

function myFunction() {
  const viewId = "###";
  const startDate = "2020-01-01";
  const endDate = "2020-06-01";

  const resource = {
    reportRequests: [
      {
        viewId: viewId,
        dateRanges: [{ startDate: startDate, endDate: endDate }],
        metrics: [
          { expression: "ga:users" },
          { expression: "ga:sessions" },
          { expression: "ga:pageviews" },
        ],
      },
    ],
  };
  const res = AnalyticsReporting.Reports.batchGet(resource, { fields: "*" });
  console.log(res);
}

Result

{
  "reports": [
    {
      "columnHeader": {
        "metricHeader": {
          "metricHeaderEntries": [
            {
              "name": "ga:users",
              "type": "INTEGER"
            },
            {
              "type": "INTEGER",
              "name": "ga:sessions"
            },
            {
              "type": "INTEGER",
              "name": "ga:pageviews"
            }
          ]
        }
      },
      "data": {
        "maximums": [
          {
            "values": ["###", "###", "###"]
          }
        ],
        "rowCount": 1,
        "totals": [
          {
            "values": ["###", "###", "###"]
          }
        ],
        "minimums": [
          {
            "values": ["###", "###", "###"]
          }
        ],
        "isDataGolden": true,
        "rows": [
          {
            "metrics": [
              {
                "values": ["###", "###", "###"]
              }
            ]
          }
        ]
      }
    }
  ]
}

Reference

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment