2
votes

I'm getting the error:

Invalid JSON payload received

When trying to create a new Apps Script file with the Apps Script API.

How do I fix that error?

function createNewFile() {
  var d,options,payload,response,theAccessTkn,url;

  theAccessTkn = ScriptApp.getOAuthToken();

  //See https://developers.google.com/apps-script/api/reference/rest/v1/projects/create
  url = "https://script.googleapis.com/v1/projects";

  d = new Date().toString().slice(0,10);

  payload = {
    "title": "AA_" + d
  }

  options = {
    "method" : "POST",
    "muteHttpExceptions": true,
    "headers": {
       'Authorization': 'Bearer ' +  theAccessTkn
     },
    "payload": JSON.stringify(payload)
  };

  response = UrlFetchApp.fetch(url,options);

  Logger.log(response)

  return response;
}

I have set the authorization scopes in the manifest file to avoid needing to add an OAuth library:

{
  "timeZone": "America/New_York",
  "oauthScopes": [
    "https://www.googleapis.com/auth/script.projects",
    "https://www.googleapis.com/auth/script.external_request"
  ],
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER"
}
1
Have you tried specifying contentType: "application/json; charset=UTF-8" in headers. UrlFetchApp defaults to application/x-www-form-urlencoded - Guillem Xercavins
No, I'll try adding the contentType. Thank you. - Alan Wells
I added "contentType": "application/json" and it now works. - Alan Wells

1 Answers

2
votes

I needed to add "contentType": "application/json" to the options.

options = {
  "method" : "POST",
  "muteHttpExceptions": true,
  "headers": {
     'Authorization': 'Bearer ' +  theAccessTkn
   },
  "contentType": "application/json",
  "payload": JSON.stringify(payload)
};