POST request with JSON data from Google Apps Script

Jump to solution
bbennett2
Community Champion

I'm working with the Canvas API and Google Apps Script (JS based). There are some examples of using Apps Script from InstructureCon 2016, but many of those were GET requests rather than POST. I also found this thread, but it hasn't resolved my issue.

I'm playing with creating a Page just because it's easy. I've tried several structures based on the suggestions I've found, none of which have worked. Using:

{
  wiki_page: {
      title: "New Page",
      body:"A new page"
   }
}‍‍‍‍‍‍

returns a 500 error. Moving wiki_page to the top level returns a 422 error. I've also tried setting the contentLength property, which also fails. URL encoding, however, works.

Is there a way to post to the API using JSON objects as payloads rather than URL encoding a string? If so, what am I overlooking?

Labels (1)
0 Likes
1 Solution
bbennett2
Community Champion

For anyone having a similar issue, I've figured it out.

To post data to external APIs, Google Apps Script uses 

UrlFetchApp.fetch(url, options)

Where the URL is a string and options is an object with several key-value tuples. The apps script syntax is non-standard and apparently doesn't reformat to meet the HTTP 1.1 encoding standard. I found https://httpbin.org/ which responds to requests by sending the request string back for logging. The error, from Apps Script in particular, had to do with the Content Type header being malformed.

Apps Script expects:

{
  Authorization: Bearer <TOKEN>,
  contentType: 'application/json'
}

and the Canvas API rejects the call. Changing the apps script object to:

{
  Authorization: Bearer <TOKEN>,
  Content-Type: 'application/json'
}

resulted in a successful request.

View solution in original post