Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
HTTP POST Request with JSON payload in Google Apps Script

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!

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!