使用Apps Script API调用scripts/:run接口时遭遇404错误
调用Google Apps Script API的run接口返回404错误的解决方法
我通过testGet()能成功获取目标脚本的函数列表(包含tester函数),但调用https://script.googleapis.com/v1/scripts/${fileId}:run接口的testRun()却返回404错误,提示"Requested entity was not found."。相关代码如下:
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); }
核心问题与解决步骤
错误根源:使用了脚本文件ID而非部署ID
scripts/:run接口要求传入的是脚本的部署ID,而非脚本文件的fileId。content接口可以用fileId获取内容,但run接口必须使用部署后的ID。操作步骤:
- 打开目标脚本文件,点击右上角「部署」→「新部署」
- 部署类型选择「API可执行」,设置版本号和描述
- 点击「部署」,复制生成的部署ID
- 将
testRun()中的fileId替换为这个部署ID
确保脚本权限范围正确
检查脚本的appsscript.json文件,确保包含所需的OAuth权限:{ "oauthScopes": [ "https://www.googleapis.com/auth/script.scriptapp", "https://www.googleapis.com/auth/script.external_request" ] }修改后重新授权脚本,确保令牌包含必要权限。
验证目标函数的可访问性
确认tester函数是全局作用域的公共函数,没有用private修饰,且参数定义与调用时的parameters数组匹配。
修正后的testRun示例
function testRun(deploymentId = "替换为你的部署ID") { const url = `https://script.googleapis.com/v1/scripts/${deploymentId}:run`; const token = ScriptApp.getOAuthToken(); const query = { "function": "tester", "parameters": [] }; const params = { method: 'POST', headers: { "Authorization": 'Bearer ' + token, "Content-Type": 'application/json' }, muteHttpExceptions: true, payload: JSON.stringify(query) }; var response = UrlFetchApp.fetch(url, params); Logger.log(response); }
内容的提问来源于stack exchange,提问作者Alex Libengood
相关产品推荐
相关产品推荐

