Google Script API routexl error 409 - javascript

I'm trying to make a script which works out the fastest route to pass multiple locations, with the help of the routexl API. However, everything I try seems to come up with an error 409 Truncated server response. My code is as follows.
function myFunctionpost() {
var url = "https://api.routexl.nl/distances";
var places = [{"address":"1","lat":"52.05429","lng":"4.248618"},{"address":"2","lat":"52.076892","lng":"4.26975"},{"address":"3","lat":"51.669946","lng":"5.61852"}];
var locations = JSON.stringify(places);
var headers = {
"Authorization":"Basic " + Utilities.base64Encode("Username:password"),
"Content-Type":"application/json"
};
var options = {
'method' : 'post',
'headers' : headers,
'contentType': 'application/json',
'payload' : locations,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
//var json = response.getContentText();
//var data = JSON.parse(json);
Logger.log(response);
}

The 409 error indicates there is no input found. I am no Google Apps expert, but the RouteXL API expects "locations" as input parameter. In your example the locations JSON is posted without the locations key.
Update: after some testing on Google Apps Script, I also found the ContentType needs to be adjusted.
Here is an example that worked for me:
function myFunctionpost() {
var url = "https://api.routexl.nl/distances";
var places = [{"address":"1","lat":"52.05429","lng":"4.248618"},{"address":"2","lat":"52.076892","lng":"4.26975"},{"address":"3","lat":"51.669946","lng":"5.61852"}];
var locations = JSON.stringify(places);
var headers = {
"Authorization":"Basic " + Utilities.base64Encode("username:password")
};
var options = {
'method' : 'post',
'headers' : headers,
'contentType': 'application/x-www-form-urlencoded',
'payload' : {'locations': locations},
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, options);
//var json = response.getContentText();
//var data = JSON.parse(json);
Logger.log(response);
}

Related

How to post an image to facebook page using Google App Script's facebook snippet?

I am trying to setup a small application based on Google App Script and Google sheets
So far I am able to get the facebook page feed and able to connect to facebook app through Oauth2 library and got the tokens
So I am struggling to write the code for posting to facebook ,
Currently I got the facebook page feeds but the post format documentation from facebook is referring to javascript SDK , and here I am not using SDK and graph API refers with POST and GET requests I think that also didn't work here .
So this is my Codes for getting facebook token and page feed .
Some one referred this as a duplicate but those question and answer doesn't fit in my question , I want facebook post format if it is with payload kindly include those payload options or someone can edit below code for POST
I am able to post to pages with the page access token not user access token
and pasting that page access token also throws the same error .
Updated Code But error appears as follows
Request failed for https://graph.facebook.com/v3.2/PAGE/feed?message=hello?access_token=TOKEN returned code 403. Truncated server response: {"error":{"message":"(#200) If posting to a group, requires app being installed in the group, and \\n either publish_to_groups permission... (use muteHttpExceptions option to examine full response) (line 53, file "FB postinf")
code updated
function example() {
var service = getService();
if (service.hasAccess())
var data = {
"message" : "Me Testing",
//"slug" : "me-testing",
// "text_to_subscribe" : "true"
};
var payload = JSON.stringify(data);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
var url = "https://graph.facebook.com/v3.2/PAGENAME/feed?message=hello?access_token=ManuallyPastedTOKEN";
// + '?access_token=' + encodeURIComponent(service.getAccessToken());
var response = UrlFetchApp.fetch(url, options);
}
This is using OAuth2 GET FEED
function sasublish(){
var service= getService()
if (service.hasAccess()) {
var url = 'https://graph.facebook.com'
+ '/pagename/feed'
+'?fields='+ encodeURIComponent("name,full_picture,message,attachments{subattachments,url}")
+'&access_token='+ service.getAccessToken();
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var jsondata = JSON.parse(json);
}
Need oAuth2 And Facebook.gs snippet you can use
.setScope('publish_pages,manage_pages,pages_show_list')
should be added to facebook.gs link to facebook.gs snippet
function example() {
var service = getService();
if (service.hasAccess())
var urls ='https://graph.facebook.com/v2.6/PAGEID?fields=access_token'; //specified page token
// var url = 'https://graph.facebook.com/v2.6/me/accounts?'; //tokens along with pages
var response = UrlFetchApp.fetch(urls, { //make url and urls changes
headers: {
'Authorization': 'Bearer ' + service.getAccessToken()
}
});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result , null, 2));
//Logger.log(JSON.stringify(result.data[0].access_token))
var datas = {
"message" : "Me Testing",
//"slug" : "me-testing",
// "text_to_subscribe" : "true"
};
var payload = JSON.stringify(datas);
var options = {
"method" : "POST",
"contentType" : "application/json",
"payload" : payload
};
var url = "https://graph.facebook.com/v3.2/PAGEID/feed"
+ '?access_token=' + encodeURIComponent(result.data[0].access_token);
// + '?access_token=' + encodeURIComponent(result.access_token);//direct pagetoken
var response = UrlFetchApp.fetch(url, options);
Logger.log('successfully posted to facebook page ',response)
}

JavaScript API post and return using Google Sheets script?

I need some help with this. I can't figure out how to print the return from an api post sent from Google Sheets (including any error codes). Posting seems to work fine as the data shows up on RequestBin when I run the function in Sheets (although there are no quotes "" around the nonce output, which I don't understand either).
I need to be able to print the return in Google Sheets (this function runs in the Script Editor) and the data needs to overflow into adjacent cells, whatever the post request returns.
This is the functional code that I have so far:
function testPost() {
var nonce = new Date().getTime();
var data = {
'key':'QrHuXeXcbN',
'signature':'c4cc0d98be8e0860391799c2ca719da5ea6514f1538c4ec69ec1c19',
'nonce':nonce
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://requestb.in/19bzt9a1', options);
}
I have tried a number of different ways to return the values but I can't figure it out.
Got it. Finally. Just needed this at the end... return response.getContentText()
function testPost() {
var nonce = new Date().getTime();
var data = {
'key':'QrHuXeXcbN',
'signature':'c4cc0d98be8e0860391799c2ca719da5ea6514f1538c4ec69ec1c19',
'nonce':nonce
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://requestb.in/19bzt9a1', options);
return response.getContentText()
}

Edit a JIRA issue through Google Apps Script - POST and JSON

I'm trying to edit an issue in JIRA through GAS.
Looking at some other people code
(for example - Using Google Apps Script to Post JSON Data)
I came up with this code:
function myFunctionpostTest() {
var username = "username";
var password = "password";
var encCred = Utilities.base64Encode(username+":"+password);
var url = "https://<base_url>/rest/api/2/issue/";
var data = {"project":{ "key": "STUDIO-4499"},"summary": "create
issue.", "issuetype": {"name": "Bug"}} ;
var payload = JSON.stringify(data);
var headers = { "Accept":"application/json",
"Content-Type":"application/json",
"Authorization":"Basic " + encCred,
};
var options = { "method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, headers);
Logger.log(response);
}
The issue is that i'm keep getting an error:
Request failed for.... returned code 405
What am i missing? why this code is not working?
Please don't answer with cURL example since it is not relevant for my issue
It seems that options is not used in the script. So how about a modification as follows? But I don't know whether the option is correct for the request. I'm sorry for this.
From :
var response = UrlFetchApp.fetch(url, headers);
To :
var response = UrlFetchApp.fetch(url, options);
If this was not useful for you, I'm sorry.
Edit :
How about the following modified script? Reference is here.
function myFunctionpostTest() {
var username = "username";
var password = "password";
var encCred = Utilities.base64Encode(username+":"+password);
var url = "https://<base_url>/rest/api/2/issue/";
var data = {
"fields": {
"project": {
"key": "STUDIO-4499"
},
"summary": "create \r\n issue.",
"issuetype": {
"name": "Bug"
}
}
};
var payload = JSON.stringify(data);
var headers = {"Authorization":"Basic " + encCred};
var options = {
"method":"POST",
"contentType": "application/json",
"headers": headers,
"payload": payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}
using this reference -
https://docs.atlassian.com/jira/REST/7.4.0/?_ga=2.214927127.1280782706.1510046526-258513799.1499779287#api/2/issue-editIssue
i've changed the data variable to
{"update":{"summary":[{"set":"Bug in business logic"}]}};
the url to
var url = "https://<base URL>/rest/api/2/issue/41335";
and changed the method in the options var to
"method":"PUT",
And now it works!

HTTP error "AUTH_CSFR_ERROR" with POST to Todoist API via Google Apps Script

I'm attempting to query items out of the Todoist API from Google Apps Script, mimicking a curl POST.
I originally tried to make OAuth2 work, but tokens were not persistent, and I instead opted for the API's method of using individual API tokens to exchange for a valid token.
Using App Script's UrlFetchApp class, I'm attempting to construct at POST request for Todoist's API to retrieve task items, and my getTodoistToken() function is indeed retrieving a valid token response, but the POST command is issuing the following 403:
"error_tag":"AUTH_CSRF_ERROR","error_code":0,"http_code":403,"error_extra":{"access_type":"web_session"},"error":"AUTH_CSRF_ERROR"}
Can anyone recommend a solution? Thanks so much, code below:
function getTodoistToken() {
var url = "https://todoist.com/api/access_tokens/migrate_personal_token";
var data = {
"client_id": "[my unique client_id]",
"client_secret": "[my unique client_secret]",
"personal_token":"[my API token from Todoist dashboard]",
"scope": "data:read"
};
var payload = JSON.stringify(data);
var headers = {
"Content-Type":"application/json",
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var json = response.getContentText();
var data = JSON.parse(json);
return(data.access_token);
}
function getTodoistTasks(){
var apiURL = "https://todoist.com/API/v7/sync";
var data = {
"token" : getTodoistToken(),
"sync_token" : '*',
"resource_types" : '["items"]'
};
var payload = JSON.stringify(data);
Logger.log(payload);
var headers = {
"Content-Type":"application/json",
};
var options = {
"method":"POST",
"contentType" : "application/json",
"headers": headers,
"payload" : payload,
"muteHttpExceptions" : true
};
var response = UrlFetchApp.fetch(apiURL, options);
Logger.log(response.getContentText());
}
I have figured out the answer. The Todoist API documentation is bit ambiguous, seeming written around POST requests, but to download (sync) a full list of tasks, a simple URL-encoded GET request, as constructed below, did the trick:
function getTodoistTasks(){
var apiURL = "https://todoist.com/API/v7/sync";
var queryString = "?token=" + getTodoistTokenRev() + "&sync_token=%27*%27&resource_types=[%22items%22]";
//Get params
var fetchParameters = {};
fetchParameters.method = 'get';
fetchParameters.contentType = 'x-www-form-urlencoded';
fetchParameters.muteHttpExceptions = true;
//make request and return
var response = UrlFetchApp.fetch(apiURL + queryString, fetchParameters);
var syncData = JSON.parse(response.getContentText());
return(syncData);
}
And if anyone is looking for an example of creating an item (a task in this case), as I was, here's the code for that (note you need to specify a date_string and due_date for it to appear in the web UI):
var API_URL = "https://todoist.com/API/v7/sync"
var BASE_QUERY = "?token=" + TOKEN
function addTask() {
// var taskName = SpreadsheetApp.getUi().prompt('What the task\'s name?')
var taskName = 'Test 1652'
var commands = encodeURI(JSON.stringify([{
"type": "item_add",
"temp_id": uuidv4(),
"uuid": uuidv4(),
"args": {
"content": taskName,
"date_string": "today",
"due_date_utc": "2017-12-2T18:00",
}
}]))
var queryString = BASE_QUERY + '&commands=' + commands
var options = {
method: 'post',
contentType: 'x-www-form-urlencoded',
muteHttpExceptions: true}
var response = UrlFetchApp.fetch(API_URL + queryString, options)
if (response.getResponseCode() !== 200) {
var content = response.getContentText()
throw new Error('URL fetch failed: ' + content)
}
var syncData = JSON.parse(response.getContentText())
return syncData
// Private Functions
// -----------------
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
} // addTask()

Google Script GET request issue

I'm trying to get a Google script (on a Google Sheet) to retrieve data from Float API. The endpoint and key are fine (tested and all works as expected on Postman) but it keeps returning 401.
Below is my code:
var API_KEY = "{ENTER YOUR KEY HERE}";
var ENDPOINT_PROJECTS = "https://api.float.com/api/v1/projects";
function getProjects() {
var headers = {
"Authorization" : "Bearer " + API_KEY,
};
var requestData = {
"method" : "GET",
"headers": headers,
"muteHttpExceptions": false
};
// Get the data
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS);
var responseCode = fetchResponse.getResponseCode();
if (responseCode == "200") {
var result = JSON.parse(fetchResponse.getContentText());
} else {
ui.alert("Error when attempting to fetch the list of spaces.");
}
}
Okay looked like I completely missed a small yet very important part...even though I created an object to hold the method and headers I was not passing this into the actual fetch!!! (This is what happens when you attempt to do a quick script at the end of the day)
So instead of this
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS);
we have this:
var fetchResponse = UrlFetchApp.fetch(ENDPOINT_PROJECTS, requestData);

Categories

Resources