Search code examples
google-apps-scriptgoogle-apigoogle-oauthgoogle-analytics-4google-analytics-data-api

403 error when attempting to fetch google analytics 4 data from app script


I am attempting to connect a custom community connector to google analytics 4 in order to get data from analytics and be able to modify it in app script and then send it to data studio. However I am having difficulty connecting and retrieving data from google analytics.

The error:

    { error: 
   { code: 403,
     message: 'Google Analytics Data API has not been used in project 640397821842 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/analyticsdata.googleapis.com/overview?project=640397821842 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.',
     status: 'PERMISSION_DENIED',
     details: [ [Object], [Object] ] } }

I have the scopes set up

 "oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/analytics.readonly"
  ],

The code i am trying to test:

function testFetch(){
  const options = {
  entry: { propertyId: 263290444},
  "dateRanges": [{ "startDate": "2020-12-01", "endDate": "2021-03-01" }],
  "dimensions": [{ "name": "country" }],
  "metrics": [{ "name": "activeUsers" }],
  // etc.
  }
  var response = UrlFetchApp.fetch(
    'https://analyticsdata.googleapis.com/v1alpha:runReport', {
    method: 'POST',
    muteHttpExceptions: true,
    headers: {
      Authorization : `Bearer ${ScriptApp.getOAuthToken()}`
    },
    contentType: 'application/json; charset=utf-8',
    payload: JSON.stringify(options)
  });
  var result = JSON.parse(response.getContentText());
  console.log(result);

Solution

  • For those with the same issue who may have overlooked some steps:

    1. Create an API project at https://console.cloud.google.com/

    2. Make sure to connect your appscript project to your cloud API project by changing the Google Cloud Platform (GCP) Project in appscript settings (It is set to a default project when you start).

    3. Enable the required APIs from the API Library in the cloud project.

    4. Now you will be able to fetchurls related to the APIs you have enabled.