I trying to write a google script to query Jira Tempo worklogs.
This is what I have so far:
function postDataForAPI() {
var payloadData = {
"taskKey" : []
};
payloadData.taskKey.push("AA-123");
var payload = Utilities.jsonStringify(payloadData);
var url = "https://api.tempo.io/core/4/worklogs/search";
var digestfull = PropertiesService.getUserProperties().getProperty("digest"); //get username and password (base64 encrypted)
var options = { "Accept":"application/json",
"Content-Type":"application/json",
"method": "POST",
"headers": {"Authorization": digestfull},
"muteHttpExceptions": true,
"payload" : payload
};
var resp = UrlFetchApp.fetch(url,options);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
return "";
}
else {
return resp.getContentText();
}
}
When I execute the above it fails.
If I use curl then I can successfully make the request (I think this is essentially the same POST):
curl -u "username:password" -X POST https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search -H 'Content-Type: application/json' -d '{"taskKey":["AA-123"]}'
Making GET requests against the same API works fine:
function getDataForAPI() {
var url = "https://api.tempo.io/core/4/worklogs/101112";
var digestfull = PropertiesService.getUserProperties().getProperty("digest"); //get username and password (base64 encrypted)
var options = { "Accept":"application/json",
"Content-Type":"application/json",
"method": "GET",
"headers": {"Authorization": digestfull},
"muteHttpExceptions": true
};
var resp = UrlFetchApp.fetch(url,options);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
return "";
}
else {
return resp.getContentText();
}
}
So I'm confident it is not Authorisation (GET request succeeds). The curl request succeeds and appears to be in the same form as the google script and yet the google script POST fails.
What do I have wrong?
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl -u "username:password" -X POST https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search -H 'Content-Type: application/json' -d '{"taskKey":["AA-123"]}'
Modification points:
It seems that "Accept":"application/json" is not used in the sample curl command.
"Content-Type":"application/json" is required to be included in the request header. But, at UrlFetchApp, the property of contentType can be used.
Utilities.jsonStringify has been deprecated. Ref
When these points are reflected in your script, it becomes as follows.
Modified script:
function postDataForAPI() {
var payloadData = { "taskKey": [] };
payloadData.taskKey.push("AA-123");
var url = "https://api.tempo.io/core/4/worklogs/search";
var digestfull = PropertiesService.getUserProperties().getProperty("digest");
var options = {
"method": "POST",
"contentType": "application/json",
"headers": { "Authorization": digestfull },
"muteHttpExceptions": true,
"payload": JSON.stringify(payloadData)
};
var resp = UrlFetchApp.fetch(url, options);
if (resp.getResponseCode() != 200) {
Browser.msgBox("Error retrieving data for url " + url + ":" + resp.getContentText());
return "";
}
else {
return resp.getContentText();
}
}
Note:
When I saw your provided curl command, it seems that the URL is different. The sample curl command uses https://api.tempo.io/rest/tempo-timesheets/4/worklogs/search. But your script uses https://api.tempo.io/core/4/worklogs/search. I'm worried about this difference. So if the above-modified script didn't work, please check the URL again.
The request of this modified script is the same as the sample curl command. But if an error occurs, please check each value like digestfull and payloadData, again.
Reference:
fetch(url, params)
Related
I'm trying to use an API, the CURL command is this one :
curl --user "<your-client-id>:<your-client-secret>" "https://api.everypixel.com/v1/faces?url=https://labs.everypixel.com/api/static/i/estest_sample3.jpg"
In my use case, I'm sending images from those type of urls : https://media-exp1.licdn.com/dms/image/C5603AQFLzBsLRsZBXQ/profile-displayphoto-shrink_800_800/0/1652669513751?e=1674086400&v=beta&t=-NC598zxFjG9fDOMJeqmLuYrP0e9NnCv92aup4MK2Wk
My problem is handling the image as the image url is not a jpg / png like the example in the CRUL command.
My script looks like this :
var url = "https://api.everypixel.com/v1/faces";
const response = UrlFetchApp.fetch(url, {
"method": "POST",
"headers": {
"Cache-Control": "no-cache",
"Content-Type": "application/json",
"user": "<your-client-id>:<your-client-secret>"
},
"muteHttpExceptions": true,
"followRedirects": true,
"validateHttpsCertificates": true,
"contentType": "application/json",
"payload": JSON.stringify({
"url": "https://media-exp1.licdn.com/dms/image/C4D03AQEnKuhl53UqCA/profile-displayphoto-shrink_800_800/0/1563935310527?e=2147483647&v=beta&t=8x-OjnqJCg6U7jt9Zm2rRscO22pG5C5QvgSh7H9lfSI"
})
});
var data = JSON.parse(response.getContentText());
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl --user "<your-client-id>:<your-client-secret>" "https://api.everypixel.com/v1/faces?url=https://labs.everypixel.com/api/static/i/estest_sample3.jpg"
In this case, how about the following modification?
Modified script:
function myFunction() {
const url = `https://api.everypixel.com/v1/faces?url=${encodeURIComponent("https://labs.everypixel.com/api/static/i/estest_sample3.jpg")}`;
const response = UrlFetchApp.fetch(url, {
"headers": { "Authorization": "Basic " + Utilities.base64Encode("<your-client-id>:<your-client-secret>") },
"muteHttpExceptions": true,
});
const data = JSON.parse(response.getContentText());
}
The sample curl command is the GET method.
url=https://labs.everypixel.com/api/static/i/estest_sample3.jpg is the query parameter.
--user "<your-client-id>:<your-client-secret>" is the basic authorization.
Note:
I think that the request of this modified script is the same as the curl command. But, if an error occurs, please confirm the values of <your-client-id>:<your-client-secret> and the URL again.
Reference:
fetch(url, params)
My coding knowledge is pretty shaky because I didn't learn it orderly.
Right now, I am trying to send an cURL Request and the documentation is:
curl https://api.at356.com/studio/v1/sd-large/complete
-H 'Content-Type: application/json'
-H 'Authorization: Bearer YOUR_API_KEY'
-X POST
-d '{"prompt": "Life is like",
"numResults": 1,
}'
this is the code
function searchFor(query) {
// Base URL to access
var urlTemplate = "https://api.at356.com/studio/v1/sd-large/complete "
// Script-specific credentials & search engine
var ApiKey = "shwMCMgEviwfz6X7Rvbtna6";
var prompt = {
"prompt": query,
"numResults": 1,
}
// Build custom cURL
var cURL = {
'method': 'POST',
"headers":{
"Content-type": "application/json",
"Authorization": ApiKey,
},
prompt,
"muteHttpExceptions": true,
"followRedirects": true,
"validateHttpsCertificates": true
};
// Perform Request
//Logger.log( UrlFetchApp.getRequest(urlTemplate, params) ); // Log query to be sent
var response = UrlFetchApp.fetch(urlTemplate, cURL,);
var respCode = response.getResponseCode();
if (respCode !== 200) {
throw new Error("Error " + respCode + " " + response.getContentText());
} else {
// Successful search, log & return results
var result = JSON.parse(response.getContentText());
Logger.log("Obtained %s search results in %s seconds.",
result.searchInformation.formattedTotalResults,
result.searchInformation.formattedSearchTime);
return result;
}
}
Can anyone tell me what I'm doing wrong and how to fix it
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script.
curl https://api.at356.com/studio/v1/sd-large/complete \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer YOUR_API_KEY' \
-X POST \
-d '{"prompt": "Life is like", "numResults": 1, }'
You have already confirmed that your this curl command works fine.
Modified script:
var query = "###"; // Please set the value.
var ApiKey = "###"; // Please set your API key.
var url = "https://api.at356.com/studio/v1/sd-large/complete";
var prompt = {
"prompt": query,
"numResults": 1,
};
var params = {
"method": "POST",
"headers": { "Authorization": "Bearer " + ApiKey },
"contentType": "application/json",
"payload": JSON.stringify(prompt),
"muteHttpExceptions": true,
};
var response = UrlFetchApp.fetch(url, params);
console.log(response.getContentText());
Note:
From your sample curl command, Authorization is like -H 'Authorization: Bearer YOUR_API_KEY'. So I modified to "headers": { "Authorization": "Bearer " + ApiKey }. If your actual API key is like Bearer ###, please modify this to "headers": { "Authorization": ApiKey }.
Reference:
fetch(url, params)
From Google Sheet's App Script, we are trying to access our database using authentication via aws-cognito-identity. I am having trouble even getting started because I am not sure how to import modules because this is not a node.js environment. Does anybody have experience doing this and would not mind sharing it?
Thanks
This is how I got this to work:
var authEndpoint = "https://[put your auth domain here].amazoncognito.com/oauth2/token";
var authClientId = "[put your Cognito client ID here]";
var authSecret = "[put your Cognito auth secret string here]";
var authExpirationTime = undefined;
var authLatestToken = undefined;
function getAuthToken() {
// If last known token is still valid, use it.
if (authLatestToken && authExpirationTime && authExpirationTime < new Date().getTime()) {
return authLatestToken;
}
// Otherwise, request new token from AWS Cognito
var params = {
method: "POST",
followRedirects: true,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic " + Utilities.base64Encode(authClientId + ":" + authSecret)
},
payload: "grant_type=client_credentials"
};
var response = UrlFetchApp.fetch(authEndpoint, params);
// Verify response
if (response.getResponseCode() !== 200) {
throw new Error("Authentication failed: HTTP Response not OK.");
}
var data = JSON.parse(response.getContentText());
if (!data.access_token) {
throw new Error("Authentication failed: No token returned.");
}
// Set internal vars and return token
authLatestToken = data.access_token;
if (data.expires_in > 0) {
authExpirationTime = new Date().getTime() + data.expires_in * 1000;
}
return authLatestToken;
}
Then you can add an authorization header with this bearer to any requests that need to be authenticated, for example:
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + getAuthToken()
},
I have the below script, that is returning a 400 - bad request.
function createIssue(e)
{
var url = "https://jira.xxxx.com/rest/api/2/issue/";
var data = {'fields': {
'project': {'key':'DWH'},
'summary':'Resttest',
'description':'test',
'issuetype':{ 'name': 'Data Requests'},
'components':[{ 'name':'Data Warehouse'}],
'fixVersions':[{ 'name':'NA'}] }};
var payload = JSON.stringify(data);
Logger.log(payload);
var headers =
{
'content-type': 'application/json',
'Accept': 'application/json',
'authorization': 'Basic xxxxxxxxxxxxxx'
};
var options =
{
'content-type': 'application/json',
'method': 'POST',
'muteHttpExceptions' : true,
'headers': headers,
'payload': payload
};
var response = UrlFetchApp.fetch(url, options);
var rc = response.getResponseCode();
var responseText = response.getContentText();
var dataAll = JSON.parse(response.getContentText());
var issueKey = dataAll.key
Logger.log(dataAll)
}
I have tested out the actual payload via cURL and it was working, so Is there something else I am missing with this script?
Thanks a million for any assistance.
Best,
Neil
EDIT:
The curl command :
curl -D- -H
"Authorization: Basic xxxxxxxxxxxx1bXBraW5zMDQh" -X POST --data
"{ """fields""": { """project""": { """key""": """DWH""" }, """summary""":
"""REST test 11111.""", """description""": """test""", """issuetype""": {
"""name""": """Data Requests""" }
,"""components""":[{ """name""":"""Data Warehouse"""}] , """fixVersions""":
[{"""name""":"""NA"""}]} }" -H "Content-Type: application/json"
https://jira.xxxxxxxxx.com/rest/api/2/issue/
I was doing some further reading and it appears that the google apps scripts are run from the google servers. My jira instance is behind a company intranet, and as such not accessible from googles servers. I also note a useIntranet feature that is depreciated. Is there any way around this?
Many thanks,
Neil
I'm trying to make calls to Basecamp's new API through Google Apps Script. GET, I can do. POST, not so much.
Starting with the path
https://basecamp.com/xxxxxxx/api/v1/projects/xxxxxxx/todolists.json
My code:
var headers = {
'User-Agent' : BCuseragent,
'Authorization' : 'Basic ' + Utilities.base64Encode(BCuser + ':' + BCpass),
'Content-Type' : 'application/json',
'Accept' : 'application/json',
'validateHttpsCertificates' : false
}
function getBC(path) {
var url = BCurl + path;
var opt = {
'headers' : headers,
'method' : "GET"
};
var response = UrlFetchApp.fetch(url, opt);
return response;
}
function postBC(path, payload) {
var url = BCurl + path;
var opt = {
'headers' : headers,
'method' : "POST",
'payload' : JSON.stringify(payload)
};
var response = UrlFetchApp.fetch(url, opt);
return response;
}
The payload I'm passing as a parameter:
{name: "foo", description: "bar"}
The getBC function works (200 OK), the postBC function returns a 403 error. Yet I am the owner of the project, and I've used curl and a Chrome REST client to confirm I can in fact POST new todolists to this project with the same authorization.
Obviously, my headers are malformed somewhere, but I can't see how.
This is a quirk of UrlFetchApp. You can't set the Content-Type using the general "headers" parameter, instead you must use the "contentType" parameter.
See the "Advanced Parameters" table here:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app#fetch(String,Object)