且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Google Apps 脚本中使用 UrlFetchApp 发出 Drive API 批处理请求

更新时间:2022-11-16 08:25:39

这个示例脚本怎么样?当我看到这个文档时,我可以发现你想要的API调用使用 multipart/mixed 发送批处理请求.这样,我可以为 Google Apps Script 创建一个示例脚本,如下所示.

How about this sample script? When I saw this document, I could find that the API calls you want to do batch request are sent using multipart/mixed. By this, I could create a sample script for Google Apps Script as follows.

function myFunction() {
  var body = [
    {
      method: "POST",
      endpoint: "https://www.googleapis.com/drive/v3/files/### fileId 1 ###/permissions",
      requestBody: {
       "role": "owner",
       "type": "user",
       "emailAddress": NEWOWNER
      }
    },
    {
      method: "POST",
      endpoint: "https://www.googleapis.com/drive/v3/files/### fileId 2 ###/permissions",
      requestBody: {
       "role": "owner",
       "type": "user",
       "emailAddress": NEWOWNER
      }
    }
  ];

  var boundary = "xxxxxxxxxx";
  var contentId = 0;
  var data = "--" + boundary + "
";
  for (var i in body) {
        data += "Content-Type: application/http
";
        data += "Content-ID: " + ++contentId + "

";
        data += body[i].method + " " + body[i].endpoint + "
";
        data += body[i].requestBody ? "Content-Type: application/json; charset=utf-8

" : "
";
        data += body[i].requestBody ? JSON.stringify(body[i].requestBody) + "
" : "";
        data += "--" + boundary + "
";
  }
  var payload = Utilities.newBlob(data).getBytes();
  var options = {
    method: "post",
    contentType: "multipart/mixed; boundary=" + boundary,
    payload: payload,
    headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
    muteHttpExceptions: true,
  };
  var res = UrlFetchApp.fetch("https://www.googleapis.com/batch", options).getContentText();
  Logger.log(res);
}

注意:

  • 请根据您的环境修改此示例脚本.
  • 如果您需要更多 API,请将元素添加到body"数组中.
  • 假设您已经启用 Drive API.
  • Drive API 在一个批量请求中最多可以使用 100 个调用.这是一个限制.
  • 对于批量请求,每个 API 调用都没有保证顺序.
  • 在我的环境中,我确认这有效.但是,如果这在您的环境中不起作用,请告诉我.我要修改.

    In my environment, I confirmed that this works. But if this didn't work in your environment, please tell me. I would like to modify.