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.
- I think I'm doing something wrong with the Authorization variable. How do I generate the latter?
- 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.