Basecamp json api post todo - json

Tried to learn the json api for Basecamp.
Get requests are working fine for me, but I cant seem to get the post requests to work.
Using Google Script.
Can anyone see the bug? I keep getting a 403, even though I am owner of the account and the project
function createBaseCampTodo(user, pw, email, appName, accountNumber,
projectNumber,todolistNumber) {
var url = "https://basecamp.com/"+accountNumber+"/api/v1/projects/"
+projectNumber+"/todolists/"+todolistNumber+"/todos.json";
var headers = {
"User-Agent": appName + " ("+email+")",
"contentType": "application/json",
"Authorization": "Basic " +
Utilities.base64Encode(user + ":" + pw)
};
var data = {
"content": "This is my new thing!",
"due_at": "2015-03-27"
};
var params = {
"method":"post",
"headers":headers,
"validateHttpsCertificates" :false,
//"muteHttpExceptions" : true,
"payload" : JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, params);
var text = response.getContentText();
Logger.log(text);
}

Buddy of mine found the bug. It should say Content-Type instead of contentType.
Points to him for his sharp mind and eyes.

Related

OAuth 2.0 is not enabled for method Error with jira cloud with App-script

I have implemented oauth2 (3LO) using App-script for integrating Google Sheet and Jira. I have set var SCOPE = read:jira-user read:jira-work write:jira-work
When I use any get request, system works fine. But when I try to make put or post request, system throws error. See this image below:
[][enter code here1]
See here my put request for edit an issue
I am not sure what is the issue here. I have checked that I have enabled oauth2 and as an administrator, I have all power. I have also proper scope. And this configuration works for any get request but it does not work with POST and PUT requests.
Could you please let me know if you have an idea or clue how I can make it work or is there anything I can check to make sure my confirmation is right for POST or PUT requests?
function updateIssue() {
var service = getService();
var issueIdOrKey = 'CP-16'
Logger.log(service.hasAccess());
if (service.hasAccess()) {
var data = `{
"summary":"New summary version 1"
}`;
var route = `/rest/api/3/issue/${issueIdOrKey}`;
var cloudid = getCloudId(service);
var url = 'https://api.atlassian.com/ex/jira/' + cloudid + route;
Logger.log(url);
var response = UrlFetchApp.fetch(url, {
'Method': 'PUT',
headers: {
//'Method': 'PUT',
'Accept': 'application/json',
'Authorization': 'Bearer ' + service.getAccessToken(),
// Convert the JavaScript object to a JSON string.
'ContentType': 'application/json' //, 'payload': JSON.stringify(data)
},
'payload': JSON.stringify(data)
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
}
}
Thank you
Modification points:
In your script, at var data = {"summary":"New summary version 1"};, data` has already been converted to the string.
When 'ContentType' is used, I thought that it was 'Content-Type'. But, in your script, I thought that 'contentType': 'application/json' can be used outside of the request header.
When these points are reflected in your script, it becomes as follows.
Modified script:
function updateIssue() {
var service = getService();
var issueIdOrKey = 'CP-16'
Logger.log(service.hasAccess());
if (service.hasAccess()) {
var data = { "summary": "New summary version 1" }; // Modified
var route = `/rest/api/3/issue/${issueIdOrKey}`;
var cloudid = getCloudId(service);
var url = 'https://api.atlassian.com/ex/jira/' + cloudid + route;
Logger.log(url);
var response = UrlFetchApp.fetch(url, {
'Method': 'PUT',
'headers': { // Modified
'Accept': 'application/json',
'Authorization': 'Bearer ' + service.getAccessToken(),
},
'contentType': 'application/json', // Added
'payload': JSON.stringify(data)
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
}
}
Note:
In this modification, it supposes that your access token and your endpoint, and your request body are valid values. Please be careful about this. If an error occurs, please show the error message and please provide the official document of the API you want to use. By this, I would like to confirm it.
Reference:
fetch(url, params)

Using Google Apps Script to Add Custom Playlist Cover Image for Spotify Playlist

I am trying to use the "Add Custom Playlist Cover Image" endpoint in the Spotify API. I have seen multiple questions on this for different languages but never a Google Apps Script example. I am quite sure that access and scope is in order, but I still get this reply back:
{
"error" : {
"status" : 401,
"message" : "Unauthorized."
}
}
Below you can see my code. I would appreciate a hint on what is wrong, or - even better - a snip of code from a working example.
imageid = '1B6I3kol0UeEWLtpNUyKmj3e6B9DEQ2hy'
var imageBytes = DriveApp.getFileById(imageid).getBlob().getBytes();
var imageEncoded = Utilities.base64Encode(imageBytes);
url = 'https://api.spotify.com/v1/playlists/' + id +'/images'
var options = {
muteHttpExceptions: true,
method: 'PUT',
headers: {
'Authorization': 'Bearer ' + service.getAccessToken(),
'Content-Type': 'image/jpeg'
},
payload: imageEncoded
};
var response = UrlFetchApp.fetch(url, options);

Changing json file creation destination from dropbox to google drive

i need to have this code have the create the json file inside of google drive instead of drop box
I have experimented with a few things but i am not quite knowledgeable enough to make this change, i would show less code but i do not know where the problem lies
function main(spreadsheet_id) {
var json_dict = fillDict(spreadsheet_id)
var json_obj = convertDictToJSON(json_dict)
sendJSONToDropbox(json_obj)
};
function sendJSONToDropbox(json_object) {
var timestamp = timeStamp()
var parameters = {
"path": "/json_jobs/rhino" + "-" + timestamp + ".json",
"mode": "add", // do not overwrite
"autorename": true,
"mute": false // notify Dropbox client
};
var headers = {
"Content-Type": "application/octet-stream",
'Authorization': 'Bearer ' + 'dropbox_access_token',
"Dropbox-API-Arg": JSON.stringify(parameters)
};
var options = {
"method": "POST",
"headers": headers,
"payload": json_object
};
var API_url = "https://content.dropboxapi.com/2/files/upload";
var response = JSON.parse(UrlFetchApp.fetch(API_url, options).getContentText());
Using the DriveApp class, it is not too difficult:
function sendJSONToGDrive(json_object) {
var timestamp = timeStamp();
var fileName = "rhino" + "-" + timestamp + ".json";
var fileContent = JSON.stringify(json_object);
var myFolder = DriveApp.getFolderById('YOUR_FOLDER_ID');
myFolder.createFile(fileName, fileContent, 'application/json');
}
You just have to replace YOUR_FOLDER_ID for your actual destination folder's id.
For more information on how to use the Drive API from Google Apps Script, I recommend you check out the following link: https://developers.google.com/apps-script/reference/drive

Stackdriver Logging API returns response code 200, but response is empty

I'm trying to fetch stackdriver logs via Stackdriver Logging API v2. I do this by making a POST request from google apps script project, in particular using UrlFetchApp. The thing is, it runs successfully, but the response shown in log is empty. However, when I made the same request using apirequest.io, curl and Google API explorer, I got the necessary response.
I searched extensively, but to no avail. Tried experimenting with header, url, but nothing.
function exportLogs () {
var options = {
"method" : "post",
"headers": {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
"resourceNames": [
"projects/MyProject"
],
"pageSize": 1,
}
var response = UrlFetchApp.fetch('https://logging.googleapis.com/v2/entries:list?key=MyApiKey', options)
Logger.log(response)
}
What I want to get is some logs, but I'm only getting {}
Issue:
Unacceptable keys are used in options object.
Solution:
payload is the only acceptable parameter for including request body.
Code:
function exportLogs() {
var options = {
method: "post",
headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() }, //Include https://www.googleapis.com/auth/cloud-platform in scopes
payload: JSON.stringify({
resourceNames: ['projects/[PROJECT_ID]'],
pageSize: 1,
}),
};
var response = UrlFetchApp.fetch(
'https://logging.googleapis.com/v2/entries:list?key=MyApiKey',
options
);
Logger.log(response);
}
To Read:
Urlfetch#params
Logging api#entriesList
Setting scopes
For some strange reason, adding an orderBy sort property in the request body object is the only way I could get results to be retrieved.
Also, a filter should be added to get only Apps Script logs.
load.filter = 'resource.type="app_script_function"';//Only from Apps Script
See example code at GitHub:
Apps Script Download Stackdriver Logs
Code:
function exportStackdriverLogs() {
var id,load,options,param,response;
id = 'Enter your Cloud Project ID here';//See your console at:
//https://console.cloud.google.com/iam-admin/settings
param = "projects/" + id;
load = {};
load.resourceNames = [param];
load.orderBy = "timestamp desc";
load.filter = 'resource.type="app_script_function"';//Only get logs that
//came from Apps Script
load.pageSize = 1;//You will probably want more than 1 but this is for an example
options = {};
options.method = "post";
options.headers = { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() };
options.payload = JSON.stringify(load);
options.muteHttpExceptions = true;
options.contentType = "application/json";
response = UrlFetchApp.fetch('https://logging.googleapis.com/v2/entries:list',options);
//Logger.log('response: ' + response.getResponseCode())
//Logger.log('content: ' + response.getContentText())
}

Connecting Google spreadsheet to Atlassian JIRA

I want to display my JIRA issues in a Google spreadsheet using Google Apps script but first i need to establish a connection with JIRA, so i went through these tutorials only to find out that the opposit is possible (JIRA connects to other applications), therefore i want to ask if there's a way to connect Google Sheets to JIRA and in that case how to get the Authentication Token ?
Request token from JIRA:
Code.gs
function requestJIRA_Token() {
var baseUrl = 'Put Base URL to JIRA here';
var theUrl = baseUrl + "/plugins/servlet/oauth/request-token";
var response = UrlFetchApp.fetch(theUrl);
Logger.log('response: ' + response);
};
JIRA OAUTH
Please find sample code to connect to JIRA and get the response as an Json Load
function seachIssuesR(j_query, maxresult) {
if (!j_query) {
Browser.msgBox("Null Query :: " + j_query);
}
var url = "https://<jiraServerName>.jira.com/rest/api/2/search?jql=" + j_query + "&startAt=0&maxResults=" + maxresult;
Logger.log(url);
if (!PropertiesService.getScriptProperties().getProperty("digest")) {
var userAndPassword = Browser.inputBox("Enter your Jira On Demand User id and Password in the form User:Password. e.g. javarohit#gmail.com:mypassword#123 (Note: This will be base64 Encoded and saved as a property on the spreadsheet)", "Userid:Password", Browser.Buttons.OK_CANCEL);
var x = Utilities.base64Encode(userAndPassword);
PropertiesService.getScriptProperties().setProperty("digest", "Basic " + x);
}
var digestfull = PropertiesService.getScriptProperties().getProperty("digest");
var headers = {
"Accept": "application/json",
"Content-Type": "application/json",
"method": "GET",
"headers": {
"Authorization": digestfull
},
"muteHttpExceptions": true
};
var resp = UrlFetchApp.fetch(url, headers);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url" + url + ":" + resp.getContentText());
return "";
} else {
json = resp.getContentText();
}
pri_list = JSON.parse(json);
return pri_list;
}