Getting error while framing request URL using appscript - api

I am trying to frame request for API using appscript.
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe"
let body = {
'"url"':'"https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg"'
};
const headers = {
'method' : 'POST',
'Host':'imagealttextcreation.cognitiveservices.azure.com',
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key':'###',
'payload': body
};
var response = UrlFetchApp.fetch(url_string,headers)
Logger.log(response)
I am getting invalid request error. But the same thing is working when i try manually(attached image for same).
Am I missing something while forming this request in the appscript?
When tried manually using the browser the functionality works. i want help in correcting the request using appscript.

From the official document, in your script, how about the following modification?
Modified script:
var url_string = "https://*.cognitiveservices.azure.com/vision/v3.2/describe";
let body = { url: "https://www.khwaahish.com/wp-content/uploads/2022/01/khwaahish-white-bg-logo.jpg" };
const options = {
headers: { "Ocp-Apim-Subscription-Key": "###" }, // Please set your value.
payload: JSON.stringify(body),
contentType: "application/json"
};
var response = UrlFetchApp.fetch(url_string, options);
Logger.log(response.getContentText())
Reference:
fetch(url, params)

Related

G-Sheet script to post a message on Guilded using its API

I am trying to create a script to post a text message in a chat on Guilded, but so far I get a "POST is not allowed"
Message should be "inPrivate" so a mention of the targeted member is required.
Google sheet test file
my script:
function message () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2ba*****";
var key = "Bearer gapi_*****"; //Q-P API temp-bot
const message = {
content : "It's alive!",
embeds :[{
author:"API",
mentions:"Raven_test",
}],
isPrivate : true,
}
const params = {
method: "POST",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
const response = UrlFetchApp.fetch(url + channelid + "/messages/", params);
var data = JSON.parse(response);
Logger.log(data);
}
Guilded's API
I don't understand what I'm doing wrong (but I'm a newbie, so it makes sens)
POST is still not working, with the same answer, however, if I use the PUT method, I can update a message if written by the same bot (I just need to add the messageid in the url after /messages/
function postmessage () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2bac803-****-****-****-a609ab9c58c4";
var key = "Bearer gapi_******"; //Q-P API temp-bot
var server = "wlVKV***"
var messageid = "ae6f1693-****-****-****-c9984d4142de";
var author = "****";
const message = {
"type": "default",
"serverId":server,
"channelId":channelid,
"content" : "test #Aaron Raven ",
"mentions":{
"users" : [{"id":author}]
},
"isPrivate":false,
"isSilent":false
};
const params = {
method: "put",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
// const response = UrlFetchApp.fetch(url + channelid + "/messages/" + messageid, params);
const response = UrlFetchApp.fetch(url + channelid + "/messages/" params);
var data = JSON.parse(response);
Logger.log(response);
Logger.log(data);
Logger.log(params);
}
Another issue (aside POST method) is that "mentions" doesn't work; it appears as basic text, and not as a user tag/link
Kind regards,

Rally API create ConversationPost

with the following code I'm trying to create new conversation post for Capability. But it says
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw '￿' [ chars read = >>>￿<<< ]
function createPost(objId, post) {
objId = "313878829904";
post = "<p>MindMap:Hello from GAS.</p>"
var url = "https://rally1.rallydev.com/slm/webservice/v2.0/conversationpost/create";
var payload = {
"ConversationPost": {
"Artifact": "/portfolioitem/capability/" + objId,
"Text": post
}
}
var method = "POST";
var options = optionsPost_(method, payload);
var response = UrlFetchApp.fetch(url, optionsPost_(method, options));
var content = JSON.parse(response.getContentText());
content.CreateResult.Errors.forEach(error => Logger.log(error));
}
function optionsPost_(method, payload) {
var rallyApiKey = "";
if (rallyApiKey != "") {
PropertiesService.getScriptProperties().setProperty("RallyApiKey", rallyApiKey);
} else {
rallyApiKey = PropertiesService.getScriptProperties().getProperty("RallyApiKey");
}
if (rallyApiKey == null) return null;
return {
headers: { "ZSESSIONID": rallyApiKey },
payload: payload,
method: method
};
}
I can't spot any problem.
Could you please help?
Thank you!
Petr
I thought that from your error message, the payload might be required to be sent as JSON data. If my guessing is correct, how about the following modification?
Modified script:
From:
return {
headers: { "ZSESSIONID": rallyApiKey },
payload: payload,
method: method
};
To:
return {
headers: { "ZSESSIONID": rallyApiKey },
payload: JSON.stringify(payload),
method: method,
contentType: "application/json"
};
Note:
In this modification, it supposes that the values of payload and rallyApiKey are valid values for using the API. Please be careful this.
When above modification was not the dierct solution of your issue, can you provide the official document of API you want to use? By this, I would like to confirm it.
Reference:
fetch(url, params) of Class UrlFetchApp
Thanks for the fast response.
With the following
var payload = {"ConversationPost":{"Artifact": "/portfolioitem/capability/"+objId,"Text": post}};
var method = "POST";
var options = optionsPost_(method, payload);
and
var options={
headers: { "ZSESSIONID": rallyApiKey },
payload: payload,
method: method,
contentType:"application/json"
};
It gives me
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '{' but saw 'h' [ chars read = >>>h<<< ]
If I change it to
var options={
headers: { "ZSESSIONID": rallyApiKey },
payload: JSON.stringify(payload),
method: method,
contentType:"application/json"
};
It gives me
Cannot parse input stream due to I/O error as JSON document: Parse error: expected '}' but saw ',' [ chars read = >>>{"headers":{"ZSESSIONID":"_ycHaCSd2QZSf8kbkQ0R1yhjohUvSzUYas0caApHt2A"},<<< ]
Only documentation I use is this:
https://rally1.rallydev.com/slm/doc/webservice/objectModel.sp#ConversationPost
I can't find any difference but this actually started working.
I believe the problem was caused by combination of mistakes. I removed one problem but perhaps add another one.
Here is a code which works.
function createPost(objId, post) {
objId = '313878829908';
post = "<p>MindMap:Hello from GAS.</p>"
var url = "https://rally1.rallydev.com/slm/webservice/v2.0/conversationpost/create";
var payload = {'ConversationPost':{'Artifact': '/portfolioitem/capability/'+objId,'Text': post}};
var method = 'POST';
//var options = optionsPost_(method, payload);
var response = UrlFetchApp.fetch(url, optionsPost_(method, payload));
var content = JSON.parse(response.getContentText());
content.CreateResult.Errors.forEach(error => Logger.log(error));
}
function optionsPost_(method, payload) {
var rallyApiKey = "";
if (rallyApiKey != "") {
PropertiesService.getScriptProperties().setProperty("RallyApiKey", rallyApiKey);
} else {
rallyApiKey = PropertiesService.getScriptProperties().getProperty("RallyApiKey");
}
if (rallyApiKey == null) return null;
var options={
'headers': {'ZSESSIONID': rallyApiKey },
'payload': JSON.stringify(payload),
'method': method,
'contentType':'application/json'
};
return options;
}
Thanks Tanaike for your help. I really appreciate it.

Image upload in React Native (Expo), using fetch results in 400 error

I have been struggling with image upload for days.
I’m using formdata like this:
let formData = new FormData();
formData.append('file', {
uri: uri,
name: `name`,
type: `image/jpeg`,
});
uri on iOS is something like asset-library://asset/path on Android it is like content://media/external/images/media/25377.
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Authorization': 'Bearer ' + token,
},
};
let response = await fetch("https://myserverurl", options)
I tried every trick reading the image as blob, removing content-type, other libraries like axios, etc…
No matter what I always get back a 400 bad file format error.
Is there something I’m missing with formdata?
(On the backend we use ASP.NET)
We have had a similar issue and were able to solve the issue the following way.
We are using a NodeJS backend (with multer) to handle the file uploads.
Expo - Mobile App Code
// extract the filetype
let fileType = uri.substring(uri.lastIndexOf(".") + 1);
let formData = new FormData();
formData.append("photo", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
let options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
We are executing the request with fetch(apiUrl, options).
The uri is the local file path (full URI e.g., file:///...) of the photo in our case and apiUrl is the endpoint of the server-side.
I think the issue might be with the type and format of uri in formdata. Have you tried to use the uri returned by the image picker?

The request sent by jQuery or JavaScript doesn't contain the Header so I received error 405

I have the HTML file and try to send the request from that page with JavaScript or jQuery, but it doesn't send the "header" to the server and it gives me the error 405. I've read related questions and try out some of them but the error code was the same. I use Fiddler to see the final request and in that there is no header as well as the method change to the OPTION!
some of the codes I used:
$.ajax({
url: "URL",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer HASHKEY');},
success: function() { alert('Success!'); }
});
or
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL", true);
xhttp.setRequestHeader("Authorization", "Bearer HASHKEY");
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function () {
var response = xhttp.responseText;
if (xhttp.readyState == 4 && xhttp.readyState == 200) {
var obj = JSON.parse(response);
// handle data as needed...
alert("obj" +obj);
}
};
Totally speaking I'm looking for a piece of code which can call API from the HTML which is content header: authorization.
Cheers
Try this:
$.ajax({
url: "URL",
type: "GET",
‎headers: {
‎"Authorization": "Bearer HASHKEY"
‎},
success: function() { alert('Success!'); }
});
Also, check that your server configuration supports CORS and explicitly allows the Authorization header.

500 error on UrlFetchApp

I am trying to pass data of a product list from Magento API to Google Spreadsheet.
No authentication was required for the Magento API as I was retrieving the data as a Guest. The API is working perfectly with RestClient.
However, 500 error occurred when fetching the REST resource from Googe Apps Script.
Exception: Request failed for
http://mymagentohost/api/rest/products?limit=2
returned code 500. Truncated server response: Service temporary
unavailable (use muteHttpExceptions option to examine full response)
This is my Google Apps Script:
function myscript() {
var url = "http://mymagentohost/api/rest/products?limit=2"
var response = UrlFetchApp.fetch(url);
var out = JSON.parse(response.getContentText());
var doc = SpreadsheetApp.create("Product Info");
var cell = doc.getRange('a1');
var index = 0;
for (var i in out) {
var value = out[i];
cell.offset(index, 0).setValue(i);
cell.offset(index, 1).setValue(value);
index++;
}
Any ideas?
Hey the trick is to add the following headers to your request
var url = "http://mymagentohost/api/rest/products?limit=2"
var params = {
headers: { 'Content-Type': "application/json", 'Accept': "application/json"},
muteHttpExceptions: true,
method: "GET",
contentType: "application/json",
validateHttpsCertificates: false,
};
var response = UrlFetchApp.fetch(url, params);
Believe the key params for Magento not to return 500 "Service temporary unavailable" are the Content-Type and Accept headers but all params mentioned in example are useful, YMMV.