16

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.

ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
Shilpi
  • 266
  • 1
  • 4
  • 8

2 Answers2

19

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.

Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
br araujo
  • 1,856
  • 2
  • 13
  • 14
  • 2
    So annoying that UrlFetchApp.fetch() disregards/overrides the "Content-Type" header specified in the "headers" option. I was tearing my hair out for over an hour trying to figure out what I was doing wrong until I stumbled across this answer! – Doktor J May 06 '15 at 18:27
  • It's important to watch that the `contentType` member is in the `options` object and not the `headers` object – luke Jul 06 '22 at 19:30
5

It is pretty counter intuitive in UrlFetchApp syntax but this:

POST /api/ra/v1/ping HTTP/1.0
Host: app.kigo.net
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
Content-Type: application/json

Translates nicely to this curl:

curl https://app.kigo.net/api/ra/v1/ping -X POST -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" -H "Content-Type: application/json"

Translates to this in Google App Script:

function myFunction() {
  var headers = {
    "Authorization": "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
  };
  var options = {
    "contentType": "application/json",
    "method": "post",
    "headers": headers,
    "payload": "test"
  };
  var response = UrlFetchApp.fetch("https://app.kigo.net/api/ra/v1/ping", options);
}
ℛɑƒæĿᴿᴹᴿ
  • 4,983
  • 4
  • 38
  • 58
user1296274
  • 189
  • 2
  • 3