Google Apps Script POST request UrlFetchApp

2020-06-23 02:17发布

问题:

I am attempting to Add Groups & Contacts to a SendHub account using their API from GoogleApps Script. I can successfully make GET requests and get JSON data back with no issues. When I attempt the POST request to add objects I have received 400, 401 & 405 errors depending upon how I prepare the data.

This gets a 400 error:

  var headers = {
    "Content-type" : "application/json"
  };
  var data = {
    "name" : "Me Testing",
    "slug" : "me-testing",
    "text_to_subscribe" : true
  };
  var payload = {
    "data" : Utilities.jsonStringify(data)
  };
  var options = {
    "method" : "post",
    "headers" : headers,
    "payload" : payload
  };
  var url = "https://api.sendhub.com/v1/groups/?username=USERNAMEWORKSFORGETREQUESTS&api_key=KEYWORKSFORGETREQEUSTS";
  var response = UrlFetchApp.fetch(url, options);

I have made several different attempts in changing the way the options object is formed and the results vary from 400, 401 or 405 errors. I am confused on how to form the proper POST request for the SendHub API which is here

I got it working shortly after this post. Here is what I did:

  var data = {
    "name" : "Me Testing",
    "slug" : "me-testing",
    "text_to_subscribe" : "true"
  };
  var payload = JSON.stringify(data);
  var options = {
    "method" : "POST",
    "contentType" : "application/json",
    "payload" : payload
  };
  var url = "https://api.sendhub.com/v1/groups/?username=GOODUSERNAME&api_key=GOODAPIKEY";
  var response = UrlFetchApp.fetch(url, options);

回答1:

I placed the answer in the edit portion of my question. I am not sure which of the three changes I made that made it work, but I left example code that did work.

 var data = {
    "name" : "Me Testing",
    "slug" : "me-testing",
    "text_to_subscribe" : "true"
  };
  var payload = JSON.stringify(data);
  var options = {
    "method" : "POST",
    "contentType" : "application/json",
    "payload" : payload
  };
  var url = "https://api.sendhub.com/v1/groups/?username=GOODUSERNAME&api_key=GOODAPIKEY";
  var response = UrlFetchApp.fetch(url, options);


回答2:

The solution you posted didn't work for me, this works for me:

 function example() {

   var payload = {
     "api_key" : "SFS1234SDF",
     "list_id" : "4"
   };

   var options = {
     "method"  : "post",
     "payload" : payload
   };

   var url        = "http://my-url.com";   
   var response   = UrlFetchApp.fetch(url, options);   

   Logger.log(response);

   return response.getContentText();

 }

Use the View -> Log option for debugging.