500 error on UrlFetchApp - api

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.

Related

Google Sheets Sentiment Analysis error over API key

Hi I've been trying to do some sentiment analysis from google sheets. Here is my code:
function getSentiment(text) {
var apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
var url = "https://language.googleapis.com/v1/documents:analyzeSentiment?key=" + apiKey;
var data = {
document: {
type: "PLAIN_TEXT",
content: text
}
};
var options = {
method: "post",
contentType: "application/json",
headers: {
"Authorization": "Bearer " + apiKey
},
payload: JSON.stringify(data)
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
return result.documentSentiment.score;
}
Here is what comes up:
Error
Exception: Request failed for https://language.googleapis.com returned code 401. Truncated server response: { "error": { "code": 401, "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or othe... (use muteHttpExceptions option to examine full response) (line 18).
I think the key is right (changed here for obvious reasons) and enabled so I'm not sure where I go from here. Any ideas? Thanks

Getting error while framing request URL using appscript

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)

ERR_ABORTED 403 (Forbidden)

I'm trying to build a program which can control my Sonos Speaker. I'm following the instructions over at https://developer.sonos.com/build/direct-control/authorize/.
The first step - getting the authorization code - is working as intended but the problem I'm facing arises when I try to send the authorization code per POST request with the following code:
const redirect_uri = "https%3A%2F%2Fsonoscontrol-c4af4.web.app%2F";
const redirect_url = "https://sonoscontrol-c4af4.web.app/";
const client_id = // API Key (deleted value for safety)
const secret = // Secret (deleted value for safety)
const auth_url = `https://api.sonos.com/login/v3/oauth?client_id=${client_id}&response_type=code&state=testState&scope=playback-control-all&redirect_uri=${redirect_uri}`;
function GetAccessToken() {
var target_url = "https://api.sonos.com/login/v3/oauth/access/";
var authCode = GetAuthCode();
var encoded_msg = btoa(client_id + ":" + secret); // base64-encodes client_id and secret using semicolon as delimiter
var params = "grant_type=authorization_code" + `&code=${authCode}` + `&redirect_uri=${redirect_uri}` + `&client_id=${client_id}`;
var myHeaders = new Headers({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST',
'Authentication': `Basic {${encoded_msg}}`,
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
});
fetch(target_url, {
method: "POST",
mode: "no-cors",
credentials: "include",
redirect: "follow",
headers: myHeaders,
body: params
}).then((res) => {
console.log(res.responseText);
}).catch(function(error) {
console.log(error);
});
}
function GetAuthCode() {
return (new URLSearchParams(location.search)).get('code'); // returns authorization code from URL
}
Now I get the following error when trying to send the POST request: POST https://api.sonos.com/login/v3/oauth/access/ net::ERR_ABORTED 403 (Forbidden)
I am using a Cloud Firebase app as webserver and added the correct redirect URL in the credentials.
What could be the problem for this error message?
I noticed a couple of things in your code that may be causing your 403 Forbidden issue.
Your "Authentication" header should be "Authorization", eg: "Authorization: Basic {YourBase64EncodedClientId:SecretGoesHere}"
Your "target_url" has a trailing slash, it should be "https://api.sonos.com/login/v3/oauth/access"
Your query parameters "params" are including the client_id on the token request, which isn't necessary, though I don't believe it will cause an error.
Addressing the above should hopefully resolve your issue!
Thanks,
-Mark

RabbitMQ HTTP API returning 401 (Unauthorized)

Using RabbitMQ localhost and trying to use his API.. when i Call from postman it's work fine.
But i'm trying to use this API inside my app code and I'm getting 401 error:
const test = {
count: 5,
ackmode: 'ack_requeue_true',
encoding: 'auto',
truncate: 50000
}
testPost() {
fetch('http://localhost:15672/api/queues/%2F/QA.MOBILE/get', {
method: 'post',
mode: 'no-cors',
body: JSON.stringify(test),
headers: {Authorization: 'Basic ' + btoa('guest:guest'), Accept: 'application/json', 'Content-Type': 'application/json'}
});
}
POST http://localhost:15672/api/queues/%2F/QA.MOBILE/get net::ERR_ABORTED 401 (Unauthorized)
I'm missing something?
thanks
I just had this problem myself. Even though my issue was not CORS related, I thought I would document the issue here in case future readers have the same problem.
My issue was that I was not correctly base64ing the user credentials. From a browser you can just call any of the RabbitMQ API endpoints like this:
http://somename:somepassword#servername:15672/api/cluster-name
But when calling it programatically, you need to remove the credentials from the url and base 64 them instead.
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("GET"), "http://servername:15672/api/cluster-name"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes($"somename:somepassword"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
var response = httpClient.SendAsync(request).Result;
if (response.IsSuccessStatusCode == true)
{
string jsonContent = response.Content.ReadAsStringAsync().Result;
}
}
}
The above code is C# but it would be the same process for Java, etc.

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.