google-apps-scripturlfetchgoogle-groups-api

Adding a few members to a Google Group in 1 URLFetchApp Call?


Is it possible to use 1 URLFetchApp.fetch call to add a handful of members to a Google group? Trying to reduce the amount of fetch calls within my app.

I am able to do 1 call per member to have them added to a Google group.

var obj = JSON.parse(jsonStr);
    for(var h=1; h< mailingData.length;h++) {
        obj["members"].push({"email":mailingData[h][column],"role":"MEMBER"});
    }
    jsonStr = JSON.stringify(obj);
    Logger.log(jsonStr);
    fetchArgs.method = "POST";
    fetchArgs.contentType = "application/json";
    fetchArgs.headers = {Authorization: 'Bearer ' + myService.getAccessToken()};
    fetchArgs.muteHttpExceptions=true;
    fetchArgs.payload = jsonStr;
    var url = 'https://www.googleapis.com/admin/directory/v1/groups/'+group+'/members';
    var res = UrlFetchApp.fetch(url, fetchArgs);

This is the print out for jsonStr:

{"members":[
{"email":"devon@myorg.com","role":"MEMBER"}, 
{"email":"jake_smith@myorg.com","role":"MEMBER"}, 
{"email":"robert_keys@myorg.com","role":"MEMBER"}
]}

The error I get when I print the response is the following: 
[19-07-31 16:21:18:451 EDT] {
 "error": {
  "errors": [
   {
    "domain": "global",
    "reason": "required",
    "message": "Missing required field: member"
   }
  ],
   "code": 400,
   "message": "Missing required field: member"
 }
}

Solution

  • In App Script you can use the fetchAll() function to make batch requests [1]. I implemented fetchAll in your code creating an empty requests array and filling it with each request for each user. The following code will work assuming you get an email from mailingData array, a correct authorization token and a existing group email in the url (i tested it with those changes):

      var requests = []
    
      for(var h=1; h< mailingData.length; h++) {
    
      var data = {"email":mailingData[h][column], "role":"MEMBER"};
      var jsonStr = JSON.stringify(data);
      var request = {};
    
      request.url = 'https://www.googleapis.com/admin/directory/v1/groups/'+group+'/members'; 
      request.method = "POST";
      request.contentType = "application/json";
      request.headers = {Authorization: 'Bearer ' + myService.getAccessToken()}; 
      request.muteHttpExceptions=true;
      request.payload = jsonStr;
    
      requests.push(request);
      }
    
      var response = UrlFetchApp.fetchAll(requests);
    

    [1] https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetchAll(Object)