How to send a JSON payload with UrlFetchApp service? How to send a JSON payload with UrlFetchApp service? json json

How to send a JSON payload with UrlFetchApp service?


I do not understand the server side error but the 'payload' parameter must be a string as specified here: https://developers.google.com/apps-script/class_urlfetchapp?hl=fr-FR#fetch.

try:

var options ={  "method" : "post",  "contentType" : "application/json",  "headers" : {    "Authorization" : "Basic <Base64 of user:password>"    },  "payload" : '{ "endDate": "2012-06-03" }'};


  • If you set payload as a String, it will be passed directly (as aUTF-8 string).
  • If you set payload as an Object, it will be sent likean HTML form (which means either 'application/x-www-form-urlencoded' if thefields are simple, or 'multipart/form-data' if the Object includes ablob/file).

For your use case (the server is expecting to receive JSON), it sounds like Utilities.jsonStringify() is the way to go.


Something like this worked for me in a similar situation:

Instead of creating payload and adding to options, I built the parameters into a string to append to the URL:

var params = "id=2179853&price=62755";

then, I appended params to the url string:

var result = UrlFetchApp.getRequest(url + '?' + params, options);

So, my options was passed containing only the header.

For my project, this worked like a charm.