Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Google Apps Script to Post JSON Data

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.

like image 855
Shilpi Avatar asked Jun 27 '13 19:06

Shilpi


People also ask

How can I get Google sheet data in JSON format using an app script?

To do this, click Extensions > Apps Script. In the resulting window, paste the following script found in this Gist. After pasting the script, click Untitled Document and then name it something like JSON EXPORT. Next, click the Save button to save your work so far.

Can you send JSON in post?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.


Video Answer


1 Answers

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);
}
like image 132
user1296274 Avatar answered Oct 10 '22 20:10

user1296274