Search code examples
google-apps-scripthttp-status-code-403google-apps-script-api

403 accessing programatically created sheets project endpoint through Apps Script


Used code to create a blank spreadsheet and obtain it's Id. Once the Id of the resource is available I want to attach a custom script to it programmatically.

  [...]
  var newSpreadsheet = SpreadsheetApp.create("Опис "+dateFormated);
  
  Logger.log(newSpreadsheet.getId());

  var url = 'https://script.googleapis.com/v1/projects/'+newSpreadsheet.getId();
  var token = ScriptApp.getOAuthToken();
  var response = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + token
    },
    muteHttpExceptions: true
  });

the request results in an error (regardless of which endpoint I call for project) The URL provided in the error message is unhelpful as it's not a project I manage. Going to it results in

You do not have sufficient permissions to view this page

You are missing at least one of the following required permissions:

Project

resourcemanager.projects.get

serviceusage.services.get

 "error": {
    "code": 403,
    "message": "Apps Script API has not been used in project 85798724816 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/script.googleapis.com/overview?project=85798724816 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": [
      {
        "@type": "type.googleapis.com/google.rpc.Help",
        "links": [
          {
            "description": "Google developers console API activation",
            "url": "https://console.developers.google.com/apis/api/script.googleapis.com/overview?project=85798724816"
          }
        ]
      }
    ]
  }

EDIT: Both the answer from puffin and TheMaster solve the problem.

The answer from TheMaster is what I wanted to do more specifically

There is also a problem with my question. I am trying to get the project for the spreadsheet before one is even created. So the correct first request to make is "POST" to "https://script.googleapis.com/v1/projects"

The solution steps:

  1. switch from "default" Google cloud project to "standard" cloud project (check the link from TheMaster)
  2. Create an API key in cloud console for the project
  var url = 'https://script.googleapis.com/v1/projects?key=[YOUR_KEY_HERE]';
  var token = ScriptApp.getOAuthToken();
  var data = {
    "parentId": "16eL4PIVFO5Zdd7r-8HhQF_4OZS7G7TbTX-pg",
    "title": "autoProject"
  };
  var response = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + token
    },
    method: 'POST',
    contentType: "application/json",
    muteHttpExceptions: true,
    payload: JSON.stringify(data),
  });

and that's how you perform a successful request to the Scripts API from Scripts itself


Solution