Search code examples
jsongoogle-apps-scriptoauth-2.0google-apps-script-api

Create new Apps Script file with the Apps Script API - Error - Invalid JSON payload received


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"
}

Solution

  • 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)
    };