How to make a Drive API batch request with UrlFetchApp in Google Apps Script

前端 未结 1 823
借酒劲吻你
借酒劲吻你 2020-12-20 01:14

I would like to know how to make a Drive API batch request with UrlFetchApp in Google Apps Script. I\'ve read the google documentation but it still isn\'t clear to me. I wan

相关标签:
1条回答
  • 2020-12-20 01:15

    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.

    Sample script :

    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 + "\r\n";
      for (var i in body) {
            data += "Content-Type: application/http\r\n";
            data += "Content-ID: " + ++contentId + "\r\n\r\n";
            data += body[i].method + " " + body[i].endpoint + "\r\n";
            data += body[i].requestBody ? "Content-Type: application/json; charset=utf-8\r\n\r\n" : "\r\n";
            data += body[i].requestBody ? JSON.stringify(body[i].requestBody) + "\r\n" : "";
            data += "--" + boundary + "\r\n";
      }
      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);
    }
    

    Note :

    • Please modify this sample script for your environment.
    • If you want more APIs, please add the elements to the array of "body".
    • It supposes that you have already enabled Drive API.
    • Drive API can be used the maximum of 100 calls in one batch request. This is a limitation.
    • For the batch request, each API call is no guaranteed ordering.

    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.

    0 讨论(0)
提交回复
热议问题