Home > Back-end >  Using GS to Import data from GA4 runRealtimeReport into Google Sheets
Using GS to Import data from GA4 runRealtimeReport into Google Sheets

Time:04-22

On Google AppsScript, I have been trying to pull real-time user data from a GA4 property into a google sheet. However, I keep getting the following error message: "API keys are not supported by this API. Expected OAuth2 access token or other authentication creden..."

Here's my attempt below:

async function test4() {
  var theAuthorization = "Bearer "   [[oAuthtoken]];
  var theRequestBody = {"dimensions":[{"name":"country"}],"metrics":[{"name":"activeUsers"}],"limit":"10","orderBys":[{"metric":{"metricName":"activeUsers"},"desc":true}],"returnPropertyQuota":true,"minuteRanges":[{"name":"1minute","startMinutesAgo":2,"endMinutesAgo":0}]};
  var theOptions = {method: 'POST',headers: {'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': theAuthorization}, body: theRequestBody};
  const response = await UrlFetchApp.fetch("https://analyticsdata.googleapis.com/v1beta/properties/[GA4property]:runRealtimeReport?key=[[API key]]", theOptions);
  Logger.log(JSON.parse(response));
}

I have already enabled the necessary APIs and scopes.

  1. I think I'm doing something wrong with the Authorization variable. How do I generate the latter?
  2. Is the API key even necessary in this case?

I have tested the request body on https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runRealtimeReport and it works.

Thank you beforehand for your input.

CodePudding user response:

Issue:

I'm not sure how you came up with [[oAuthtoken]], but I guess it's not a valid oAuthToken.

In order to get that, you should:

  • Make sure that the script is authorized with one of the method scopes (e.g. https://www.googleapis.com/auth/analytics.readonly). You could, for example, set that as an explicit scope.
  • Use ScriptApp.getOAuthToken to get the token (e.g. const oAuthtoken = ScriptApp.getOAuthToken();).

Also, you're right, the API key is not necessary. Since you provide an OAuth token, the API key is completely superfluous.

Use Analytics Data Service:

A much easier way to call this API is to use Analytics Data Service:

AnalyticsData.Properties.runRealtimeReport(theRequestBody, yourProperty);

In this case, Apps Script handles authorization for you, so you don't have to worry about OAuth tokens.

Also, since it's an advanced service, you'll first have to enable it.

  • Related