I'm having trouble getting Google App Script's UrlFetchApp class to correctly format a JSON payload in a HTTP request.
Here's how I'm formatting the payload:
var data = {
'RequestData': {
'ItemNumber': '1',
'StockItemId': '2',
'ImageUrl': 'www.example.com'
}
};
var payload = JSON.stringify(data);
Surely enough, Logger.log(payload)
returns:
{"RequestData":{"ItemNumber":"1","StockItemId":"2","ImageUrl":"www.example.com"}}
However, when I integrate this with the actual request:
var url = 'https://example.com/api/method';
var options = {
'method': 'post',
'contentType':'application/json',
'payload': payload,
'muteHttpExceptions': true
};
and examine Logger.log(UrlFetchApp.getRequest(url, options).toSource())
, I get this:
({method:"post",
payload:"{\"RequestData\":{\"ItemNumber\":\"1\",\"StockItemId\":\"2\",\"ImageUrl\":\"www.example.com\"}}",
followRedirects:true,
validateHttpsCertificates:true,
useIntranet:false, contentType:"application/json",
url:"https://example.com/api/method"})
i.e. all the quotes are escaped, as if JSON.stringify is being called twice on the payload.
I thought GAS might be calling an equivalent of JSON.stringify on the payload behind the scenes because contentType is specified as "application/json" but if I pass the data raw without stringifying it, I get:
({method:"post",
payload:"RequestData=%7BItemNumber%3D1,+StockItemId%3D2,+ImageUrl%3Dwww.example.com%7D",
followRedirects:true,
validateHttpsCertificates:true,
useIntranet:false, contentType:"application/json",
url:"https://example.com/api/method"})
which is weird and (I'm pretty sure) an invalid JSON string. Either way, the request fails (400 Bad Request) and I'm pretty sure it's because I can't get the JSON across properly.
All the docs and examples I can find seem to suggest that JSON.stringify(payload)
is the way to go but I'm clearly having issues...
Have also had the thought that this might have something to do with the implementation of the .toSource()
method and that my problem might lie elsewhere but I have no way of knowing / otherwise being able to check the request body I'm sending.
Any insight would be much appreciated!