Apps Script API Getting a 404 error when using `https://script.googleapis.com/v1/scripts/${fileId}:run`

163 views Asked by At

I'm trying to run a function in another script file. Here is my code:

function testGet(fileId = "1JjRpqhqJMvXETMMzlYFnuulni6DuwLl9jxlYnGNNm45NwzPXdtcWOK0a") {
  const url = `https://script.googleapis.com/v1/projects/${fileId}/content`;
  const token = ScriptApp.getOAuthToken();
  const params = {
    method: 'GET',
    headers: {
      "Authorization": 'Bearer ' + token,
      "Content-Type": 'application/json'
    }
  };
  var response = UrlFetchApp.fetch(url, params);
  Logger.log(response);
}

function testRun(fileId = "1JjRpqhqJMvXETMMzlYFnuulni6DuwLl9jxlYnGNNm45NwzPXdtcWOK0a") {
  const url = `https://script.googleapis.com/v1/scripts/${fileId}:run`;
  const token = ScriptApp.getOAuthToken();
  const query = {
    "function": "tester",
    "parameters": [],
  }
  const params = {
    method: 'POST',
    headers: {
      "Authorization": 'Bearer ' + token,
      "Accept": "application/json",
      "Content-Type": 'application/json'
    },
    muteHttpExceptions: true,
    payload: JSON.stringify(query)
  };
  var response = UrlFetchApp.fetch(url, params);
  Logger.log(response);
}

I am using testGet() to make sure the API is able to see the script file and it's functions. This returns the following response:

..."functionSet": {
        "values": [
          {
            "name": "tester"
          },
          {
            "name": "firstRun"
          }
        ]
      }

testRun() returns:

{
  "error": {
    "code": 404,
    "message": "Requested entity was not found.",
    "status": "NOT_FOUND"
  }
}

I can't figure out why the API POST request can't find the function I am calling when it is listed in the GET request.

Here is the API documentation: https://developers.google.com/apps-script/api/reference/rest

2

There are 2 answers

2
cnavar On BEST ANSWER

I tried replicating your issue and instead of using Script ID, I used the deployment ID of the apps script function that I want to access in the main/primary script.

Deploy > Manage Deployments

enter image description here

Give it a try and I'm glad to know how it went!

Execute Functions with the Apps Script API

You can also check out this SO post, which might be helpful.

1
Cooper On

This works for me:

function testGet() {
  const scriptId = gobj.globals.scriptid;
  const url = "https://script.googleapis.com/v1/projects/" + scriptId + "/content?fields=files(functionSet%2Cname%2Ctype%2Csource)";
  const options = { "method": "get", "headers": { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } };
  const res = UrlFetchApp.fetch(url, options);
  let data = JSON.parse(res.getContentText());
  Logger.log(data)
}

Perhaps you need to specify some fields