Json – Using Google Apps Script to Post JSON Data

content-typegoogle-apps-scripthttp-postjirajson

I am trying to post JSON data to the URL from google script but getting the above error:

Server response : HTTP Status 415 – Unsupported Media Type

My code:

function myFunctionpost() {
  var url = "http://abc.xyz.org/jira/rest/api/2/issue";
  var data = {
    "project": {
      "key": "KEY"
    },
    "summary": "create issue.",
    "description": "Creating of an issue from google spreadsheet using the REST API",
    "issuetype": {
      "name": "Bug"
    }
  };
  var payload = JSON.stringify(data);

  var headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": "Basic _authcode_"
  };

  var options = {
    "method": "POST",
    "headers": headers,
    "payload": payload
  };
  var response = UrlFetchApp.fetch(url, options);
  Logger.log(response);
}

I tried changing the content-type but didn’t work.

The authcode is working because I am able to GET from the URL.

Best Answer

Add to your options a contentType object like this:

var options = {
  "method": "POST",
  "contentType": "application/json",
  "headers": headers,
  "payload": payload
};

ContentType is one of the advanced parameters that the fetch method accepts. See more here.