Christian
Christian

Reputation: 11

Google App Scripts - UrlFetchApp.Fetch unable to post

I am trying to have GAS trigger an external POST request to the Adverity Datatap management API to trigger a fetch (https://help.adverity.com/hc/en-us/articles/360009502839-Datastreams-Triggering-a-Fetch) however, the response I'm receiving indicates that a GET request is being sent instead of a POST request. Is there something specific that seems off in the code below?

function triggerFetch() {
  var myURL = 'https://YOUR_STACK.datatap.adverity.com/api/datastreams/684/fetch'
  var options, thisDate, headers, data;

  thisDate = Utilities.formatDate(new Date(), "EST-5", "yyyy-MM-dd") + 'T00:00:00Z';
  headers = {
    'Authorization':'Token XXXXXXXXXXXXXXXXXXXXXXXXXX'
  };
  data = {
    'start':thisDate
    ,'end':thisDate.replace('T00','T12')
  }
  options = {
    method:'POST'
    ,muteHttpExceptions: true
    ,headers:headers
    ,'Content-Type':'application/json'
    ,payload:JSON.stringify(data)
    }
  var response = UrlFetchApp.fetch(myURL,options);
  Logger.log(response);
}

edit: for additional context, this is the working cURL output from postman

curl --location --request POST 'https://YOUR_STACK.datatap.adverity.com/api/datastreams/684/fetch/' \
--header 'Content-Type: application/json' \
--header 'Authorization: Token XXXXXXXXXXXXXXXXXXXXXXXXXX' \
--data-raw '{
    "start": "2021-02-16T00:00:00Z",
    "end": "2021-02-16T12:00:00Z"
}'

Upvotes: 1

Views: 785

Answers (2)

Christian
Christian

Reputation: 11

I was able to figure this out and am posting an answer in case it becomes relevant for anyone else. The datatap API documentation specifies that the URL should end with a trailing "/". Without this last character, a redirect occurs and the http method is reset to GET instead of POST.

Upvotes: 0

Jason E.
Jason E.

Reputation: 1221

You can try making options contain string with ""(double quotes) instead of ''(single quotes). It should look like this:

  options = {
    "method" :"POST"
    ,"muteHttpExceptions": true
    ,"headers": headers
    ,"contentType":"application/json"
    ,"payload":JSON.stringify(data)
    }

Upvotes: 1

Related Questions