How to use Google Apps Script to create issues in Redmine? - google-apps-script

I'm trying to create an issue in Redmine using Google Apps Script, the code is following:
function create_issue() {
var payload = {
'project_id': 'helpdesk',
'subject': 'This is a test ticket',
'description': 'This is just a genius test ticket',
'category_id': 1
};
var headers = {
'X-Redmine-API-Key': '<myapikey>',
'Content-Type': 'application/json'
};
var url = 'http://myredmine.com/issues.json';
var options = {
'method': 'POST',
'headers': headers,
'payload': payload,
//uteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
Every time I ran that script, it threw the following exception:
Execution failed: Request failed for http://myredmine.com/issues.json
returned code 422. Truncated server response: {"errors":["Subject
can't be blank"]} (use muteHttpExceptions option to examine full
response) (line 25, file "Code") [0.645 seconds total runtime]
But as you see, the "subject" parameter was passed in the payload already. What am I missing?
Thanks,
Trinh

I found the problem, I need to indicate the issue in the payload:
function create_issue() {
var issue = {
"description": "Test ticket",
"subject": "Genius ticket"
}
var payload = {
"issue": issue,
"key": "<myapikey>",
"project_id": "helpdesk",
};
payload = JSON.stringify(payload);
var headers = {
'X-Redmine-API-Key': '<myapikey>',
'Content-Type': 'application/json'
};
var url = 'http://myredmine.com/issues.json';
var options = {
'method': 'POST',
'headers': headers,
'payload': payload,
'contentType': 'application/json',
//'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
And it works!

Related

Google Apps Script and Google Search Console API

I need to access datas from Search Console using Apps Script.
I tried a loads of things but nothing worked.
I'm using this doc : https://developers.google.com/webmaster-tools/v1/searchanalytics/query
Here are some things I tried :
function authenticate() {
return gapi.auth2.getAuthInstance()
.signIn({scope: "https://www.googleapis.com/auth/webmasters https://www.googleapis.com/auth/webmasters.readonly"})
.then(function() { console.log("Sign-in successful"); },
function(err) { console.error("Error signing in", err); })}
function loadClient() {
gapi.client.setApiKey("YOUR_API_KEY");
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/searchconsole/v1/rest")
.then(function() { console.log("GAPI client loaded for API"); },
function(err) { console.error("Error loading GAPI client for API", err); })}
function execute() {
return gapi.client.webmasters.searchanalytics.query({
"resource": {}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
},
function(err) { console.error("Execute error", err); })}
Other try:
function searchConsoleQuery() {
var service = getService();
var apiURL =
'https://www.googleapis.com/webmasters/v3/sites/[SITE_URL]/searchAnalytics/query';
var headers = {
'Authorization': 'Bearer ' + service.getAccessToken(),
'contentType':'application/json',
'startDate':'20019-10-01',
'endDate':'2019-10-10'};
var options = {
'payload': JSON.stringify(headers),
'method' : 'POST',
'muteHttpExceptions': true};
var response = UrlFetchApp.fetch(apiURL, options);
var json = JSON.parse(response.getContentText());
Logger.log(json)}
Modification points:
In your script, headers is used to payload.
'startDate' is 20019-10-01.
When these points are reflected in your script, it becomes as follows.
Modified script:
function searchConsoleQuery() {
var siteUrl = "###"; // Please set your site URL.
var service = getService();
var apiURL = `https://www.googleapis.com/webmasters/v3/sites/${encodeURIComponent(siteUrl)}/searchAnalytics/query`;
var options = {
'method': 'POST',
'muteHttpExceptions': true,
'headers': { 'Authorization': 'Bearer ' + service.getAccessToken() },
'contentType': 'application/json',
'payload': JSON.stringify({
'startDate': '2019-10-01',
'endDate': '2019-10-10'
})
};
var response = UrlFetchApp.fetch(apiURL, options);
var json = JSON.parse(response.getContentText());
Logger.log(json)
}
Note:
In this modification, it supposes that Google Search Console API has already been enabled at API console and also siteUrl and your access token of service.getAccessToken() are the valid values for using the API. Please be careful about this. When I tested this modified script with my site URL, I confirmed that the values are returned without error. So, if an error occurs, please confirm the condition of API in your API console and your values again.
If no values are returned, please modify 'startDate': '2019-10-01' and 'endDate': '2019-10-10' and test it again.
References:
Search Analytics: query
fetch(url, params)

put works in postman but not google scripts

I am trying to push sheets data from a quiz to an api. The put works fine in postman but I can't seem to get it to work in google scripts.
Postman
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
myHeaders.append("Authorization", "Basic bmljazpuaWNr");
myHeaders.append("Cookie", "FB_ResponseHeaders=%7b%22X-XSS-Protection%22%3a%7b%22Key%22%3a%221%3b+mode%3dblock%22%2c%22Value%22%3a%225C-58-58-82-DB-E9-4D-AD-BF-23-F8-5A-65-1E-EE-7B-96-94-7C-E6%22%7d%2c%22X-Content-Type-Options%22%3a%7b%22Key%22%3a%22nosniff%22%2c%22Value%22%3a%22E9-85-E8-2B-38-74-3B-AA-71-5A-41-1D-65-49-06-A7-FF-B3-D2-57%22%7d%2c%22Strict-Transport-Security%22%3a%7b%22Key%22%3a%22max-age%3d31536000%3b+includeSubDomains%22%2c%22Value%22%3a%221D-31-04-88-80-8A-6A-27-8E-2D-72-C5-32-98-74-A9-F8-E8-0C-E7%22%7d%7d; fbd_cooked=!/muNNuj9SlbMhC0PporV/qqu1cgGGvczJaMywTIzq+9GDRYedxCjdCU9X3WnSt1ijLXqndrZJ1DCTVw=");
var raw = JSON.stringify({
"fieldName": "SingleLineText5",
"fieldValue": "question1test"
});
var requestOptions = {
method: 'PUT',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
Google Scripts
// put em in a payload
var payload = {
"fieldName": "SingleLineText7",
"fieldValue": "question1googleSheet" }
var encodedAuth = Utilities.base64Encode("nick:nick");
var headers = [{"Authorization" : "Basic " + encodedAuth},{"Content-Type":"application/json"}];
var options = {
'method': 'PUT',
'body': JSON.stringify(payload),
'headers': headers,
'redirect': 'follow'
}
response = UrlFetchApp.fetch(url, options);
//log the response
Logger.log(JSON.stringify(response));
Am receiving
Exception: Attribute provided with invalid value: headers
If i remove the "Content-Type" I get no error but send no data just returns {}
According to the documentation you are using the wrong parameter. It should be:
const options = {
method : "PUT", // this was correct
payload: JSON.stringify(payload), // correct this
followRedirects : true, // correct this
headers: headers
}

LinkedIn API OAUTH returning "grant_type" error

I am pretty new to coding, but trying to write a simple script using LinkedIn's API that will pull an organizations follower count into google app script. Before I can even query the API, I have to authenticate using oath explained in the LinkedIn API here.
This function returns with an error response
function callLinkedAPI () {
var headers = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
"headers": headers,
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}
When I try sending the headers through I get this error as a response
{"error":"invalid_request","error_description":"A required parameter \"grant_type\" is missing"}
grant_type, client_id, client_secret do not go in the header of the request. Instead, try to put them in the body of the POST request with the content type x-www-form-urlencoded as you already had in the headers of the code you posted.
For example:
fetch('https://www.linkedin.com/oauth/v2/accessToken/', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: new URLSearchParams({
grant_type: 'client_credentials',
client_id: '78ciob33iuqepo',
client_secret: 'deCgAOhZaCrvweLs'
})
})
.then(response => response.json())
.then(responseData => {
console.log(JSON.stringify(responseData))
})
Using Apps Script you should send the payload like so:
Example:
function callLinkedAPI() {
var payload = {
"grant_type": "client_credentials",
"client_id": "78ciob33iuqepo",
"client_secret": "deCgAOhZaCrvweLs"
}
var url = `https://www.linkedin.com/oauth/v2/accessToken/`
var requestOptions = {
'method': "POST",
'contentType': 'application/x-www-form-urlencoded',
'muteHttpExceptions': true,
"payload":payload
};
var response = UrlFetchApp.fetch(url, requestOptions);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(json)
}

Error while calling freshchat APIs from google apps script

I am trying to call FreshChat API from google apps script. GET request of outbound-messages is working fine but POST request is failing with error
Exception: Request failed for http://api.in.freshchat.com returned code 400. Truncated server response: {"success":false,"errorCode":0,"errorMessage":"HTTP 405 Method Not Allowed","errorData":null,"errorName":null} (use muteHttpExceptions option to examine full response)
Below are the details of request
function myFunctiontest() {
var url = "http://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = {
'Authorization': 'Bearer XXXXXX',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
'method': 'post',
'contentType': 'application/json',
'headers': headersPOST,
'payload': JSON.stringify(bodyPayload),
'muteHttpExceptions':true
};
var response = UrlFetchApp.fetch(url, options);
console.log(response.getAllHeaders());
Logger.log(JSON.parse(response.getContentText()));
}
Same headers are working for GET request. Also same post request is working from POSTMAN.
Freshchat support helped for solving the issue.
There are two major changes
use https instead of http
Added contentType inside headers.
function myFunctiontest() {
var url = "https://api.in.freshchat.com/v2/outbound-messages/whatsapp";
var headersPOST = 'Bearer XXXXXX';
var bodyPayload = {"from": {"phone_number": "+XXXXXX"},"provider": "whatsapp","to": [{"phone_number": "+ XXXXX"}],"data": {"message_template": {"storage": "none","template_name": "XXXXXX","namespace": "XXXXX","language": {"policy": "deterministic","code": "en"},"template_data": [{"data": "XXXXX"}]}}};
var options = {
method: 'POST',
//content-type: 'application/json',
headers: { Authorization: headersPOST, 'content-type': 'application/json'},
payload: JSON.stringify(bodyPayload),
muteHttpExceptions:true
};
var response = UrlFetchApp.fetch(url, options);
var text = response.getResponseCode();
}

Posting to Bitly api with Google App Script returns 403

Hey Stackoverflow fellows!
I have been trying to writing an automation for my google sheets using an api from bit.ly to shorten my tons of link. Right now, I am at the fundamental stage and trying to log what the api return to me. Could you guys help an see what is wrong with the code? I am expecting the 200 returning back to me but it keep returning 403 forbidden to me.
var form =
{"long_url": "https://dev.bitly.com", "domain": "bit.ly", "group_guid": "MY GROUP ID" };
var option = {'header':'Authorization: Bearer{MY TOKEN}',
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(form)
};
var response = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/shorten', option);
Logger.log (response);
}
P.S. I tried to further expand the code by using adding title (succeeded) and customized link (short half // after bit.ly/ ). The second part keep return me 404. Or should I use Post/custom_bitlinks instead?
Here is my current code:
function bitlyori (i, title){
var form = {
"group_guid": "MINE",
"domain": "bit.ly",
"long_url": i,
"title" : title
};
const MY_TOKEN = "MINE";
const option = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(form),
};
var result = UrlFetchApp.fetch('https://api-ssl.bitly.com/v4/bitlinks', option);
return (JSON.parse(result.getContentText()));
}
function bitly(url,title,custom) {
var temp = bitlyori(url, title);
var form_2 = {
"custom_bitlinks": [temp] ,
};
const MY_TOKEN = "MINE";
const option_2 = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'patch',
payload: form_2};
var temp_link = 'https://api-ssl.bitly.com/v4/bitlinks/'+ JSON.stringify(temp)["id"];
var result_2 = UrlFetchApp.fetch(temp_link, option_2);
return (JSON.parse(result_2.getContentText()));
}
Headers should be a object with key "headers" inside options:
const MY_TOKEN = "dfjkgsa";
const option = {
headers: { Authorization: `Bearer ${MY_TOKEN}` },
method: 'post',
contentType: 'application/json',
payload: JSON.stringify(form),
};
See:
Urlfetchapp ยง Advanced parameters