restgoogle-apps-scriptgoogle-apps-script-api

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


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


Solution

  • 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.