apipostgoogle-apps-scripturlfetchjive

Google App Script Silently fails to POST, Curl Works


Curl is posting but Google AppScript is not with the same credentials.

Am trying to get google app script to post the current document as html content to a new Jive Document

// The following curl command works flawlessly

curl -u USERNAMEHERE:PASSWORDHERE -H "Content-Type: application/json" --data '{ "type": "document", "content": { "type": "text/html", "text":"<h1>HOORAY</h1> a Document is born"}, "subject": "TEST WORKED"}' https://MYJIVEURL.com/api/core/v3/places/XXXXXXXX/contents

// Apps Script is now throwing a 401 and failing

function pleaseWork() {
  var encode = Utilities.base64Encode('USER:PASS', Utilities.Charset.UTF_8);
  var docbody = DocumentApp.getActiveDocument().getBody();
  var subject = DocumentApp.getActiveDocument().getName();
  var url = "https://JIVEURL/api/core/v3/places/XXXXXX/contents";

  var option = {
    authorization: "Basic " + encode,
    contentType: "application/json",
    method: 'post',
    payload: JSON.stringify({
      subject: subject,
      type: "document",
      content: {
        type: 'text/html',
        text: docbody
      },
    })
  }

  var response = UrlFetchApp.fetch(url, option).getContentText()

}```




Theres no other errors to speak of in the AppScript editor. So I must be leaving something out. I just don't know what that is

Solution

  • Part 1 - payload

    params object has a parameter called "payload" that should contain data you are going to send as a stringified JSON. Thus, instead of direct reference of the content, subject and type, you should do the following (btw, content type for UrlFEtchApp can be set via contentType parameter and the method via the corresponding parameter):

    var option = {
      //other parameters here;
      method : 'post',
      contentType : 'application/json',
      payload : JSON.stringify( {
      content : '',
      subject : '',
      type    : ''
      } )
    }
    

    Part 2 - headers

    Though it may seem arbitrary, not all of the parameters should be moved to top-level properties of the params object. There is a closed set of properties that can be set this way (see reference). Authorization should still be set as a header, thus:

    var option = {
      //other parameters here;
      headers : {
        Authorization : 'Basic ' + yourAuth
      },
      method : 'post',
      contentType : 'application/json',
      payload : JSON.stringify( {
        content : '',
        subject : '',
        type    : ''
      } )
    }
    

    Useful links

    1. UrlFetchApp.fetch() reference;