Ad

How To Send API Call To The Google Analytics API With Multiple Metrics Using Javascript

I'm using Node.js and Javascript to make API call to the Google analytics API.

const result = await google.analytics("v3").data.ga.get({
      ...defaults,
      "start-date" : "2019-01-01",
      "end-date" : "2019-02-01",
      metrics: ["ga:users", "ga:pageviews"]
    });

It works well when I use only 1 parameter as argument. But when I create an array of metrics like this it responds with the result to only one of them. The documentation says that actually I can send multiple metrics at once, but I don't know how to do it using JSON object. How should I do it?

Ad

Answer

The metrics parameter in the Google analytics api v3 is not an array its a string

 metrics: "ga:users, ga:pageviews"

Google Analytics api v4

you may want to consider updating to the newer version of the api

Hello analytics v4

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Hello Analytics Reporting API V4</title>
  <meta name="google-signin-client_id" content="<REPLACE_WITH_CLIENT_ID>">
  <meta name="google-signin-scope" content="https://www.googleapis.com/auth/analytics.readonly">
</head>
<body>

<h1>Hello Analytics Reporting API V4</h1>

<!-- The Sign-in button. This will run `queryReports()` on success. -->
<p class="g-signin2" data-onsuccess="queryReports"></p>

<!-- The API response will be printed here. -->
<textarea cols="80" rows="20" id="query-output"></textarea>

<script>
  // Replace with your view ID.
  var VIEW_ID = '<REPLACE_WITH_VIEW_ID>';

  // Query the API and print the results to the page.
  function queryReports() {
    gapi.client.request({
      path: '/v4/reports:batchGet',
      root: 'https://analyticsreporting.googleapis.com/',
      method: 'POST',
      body: {
        reportRequests: [
          {
            viewId: VIEW_ID,
            dateRanges: [
              {
                startDate: '7daysAgo',
                endDate: 'today'
              }
            ],
            metrics: [
              {
                expression: 'ga:sessions'
              }
            ]
          }
        ]
      }
    }).then(displayResults, console.error.bind(console));
  }

  function displayResults(response) {
    var formattedJson = JSON.stringify(response.result, null, 2);
    document.getElementById('query-output').value = formattedJson;
  }
</script>

<!-- Load the JavaScript API client and Sign-in library. -->
<script src="https://apis.google.com/js/client:platform.js"></script>

</body>
</html>
Ad
source: stackoverflow.com
Ad