Constructing the UrlFetchApp request to obtain an Access Token from ChinaBrands API - api

function getAccessToken()
{
var url = "https://gloapi.chinabrands.com/v2/user/login";
var data = {
"email": EMAILID,
"password": PWD,
"client_id": APIKEY
}
var payload = {
"data": data,
"signature": Utilities.base64Encode(data + SECRETKEY)
}
var options = {
"method": "post",
"contentType": "application/json",
"payload": payload
};
var json = UrlFetchApp.fetch(url, options).getContentText();
Browser.msgBox(json);
}
Please see attached documentation API screenshot link below.
I am trying to connect ChinaBrands API using google apps script.
I am getting error which says "{"status":0,"msg":"Requested info is empty","errcode":10006}"
See this Image : Documentation API to get AccessToken:

The documentation is a bit misleading. You need to make POST request with Content-Type: application/x-www-form-urlencoded. The request data field should be a string with your data in JSON format. I guess depending on language/libraries you use, you might need to URL encode the JSON data before making the request.
The resulting request should look like:
POST https://gloapi.chinabrands.com/v2/user/login
...
Accept: */*
Content-Type: application/x-www-form-urlencoded
signature=<md5 of string containing data in json + client secret>&data=%7B%22email%22%3A+%22name%40example.com%22%2C+%22password%22%3A+%2222password1%22%2C+%22client_id%22%3A+%1337%22%7D
Python 3 example with requests library:
url = "https://gloapi.chinabrands.com/v2/user/login"
data = {...}
json_data = json.dumps(data)
signature = md5((json_data + client_secret).encode('utf')).hexdigest()
response = requests.post(url, data={'signature': signature, 'data': json_data})

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

Issue sending in method to UrlFetchApp.fetch in GAS

Stupid question here, but I am pulling my hair out (i'm bald) as to what I could possibly be doing wrong. I am doing a UrlFetchApp.fetch in google app scripts:
var result = UrlFetchApp.fetch(url, { headers: headers });
When using this as my headers, it works:
var headers = {
Authorization: 'Bearer ' + getAccessToken()
}
Now I need to pass in 'method' as 'PUT' instead of the default of 'GET' (above), and and trying like this:
var headers = {
method : 'put',
headers : {
Authorization: 'Bearer ' + getAccessToken()
}
}
When I try sending this, it is not finding the token:
Exception: Request failed for https://api.spotify.com returned code 401. Truncated server response: {
"error": {
"status": 401,
"message": "No token provided"
}
How can I format the headers so that I can pass in the Authorization with token and also pass in 'method' as 'PUT'?
I see in the URLFetchApp.Fetch documentation for Google, that this is passed into options:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
headers Object a JavaScript key/value map of HTTP headers for the request
method String the HTTP method for the request: get, delete, patch, post, or put. The default is get.
Thank you so much for any help!
phi
I believe your goal is as follows.
You want to convert the following curl command to Google Apps Script. Ref And, from I know the call works with a simple GET method, your access token is valid.
curl --request PUT \
--url https://api.spotify.com/v1/me/player/play \
--header 'Authorization: ' \
--header 'Content-Type: application/json' \
--data '{
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
}'
In this case, how about the following sample script?
Sample script:
Please modify data for your actual situation.
var data = {
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
};
var options = {
method: 'put',
headers: { "Authorization": 'Bearer ' + getAccessToken() },
contentType: "application/json",
payload: JSON.stringify(data)
};
var url = "https://api.spotify.com/v1/me/player/play";
var res = UrlFetchApp.fetch(url, options);
console.log(res.getContentText());
Note:
I think that this request is the same as the curl command. But if an error occurs, please check the access token and the values in data, again.
References:
Start/Resume Playback
fetch(url, params)

How would I use an API key to locate the JSON of a website

I'm trying to find some JSON documentation for FortniteTracker.com's API, and I've already got my API Key for the website. How would I use the API Key in a URL to find the JSON?
Try including the API Key in the headers of your request.
You should really look at the documentation though, I'm sure they have some examples on how to do it.
EDIT:
let apiKey = "YOUR API KEY GOES HERE"
const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://api.fortnitetracker.com/v1/powerrankings/pc/NAE/Ninja"
fetch(proxyurl + url, {
method: "GET",
headers: {
"Content-Type": "application/json",
"TRN-Api-Key": apiKey,
}
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
});
This code works in my browser. You needed to add your API key as a 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.

Trouble with Mashape API using Google Apps Script

I've been using Google Apps Script for a little while now, but some how always get hung up on this payload thing. I'm just trying to to do a basic api call to mashape. Since it is a post call I'm pretty sure I should use the payload in the parameter-options, but just not really sure what's throwing me my error. Here is my code:
function mashapeTextSentiment(text){
var key = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
var url = "https://japerk-text-processing.p.mashape.com/sentiment/";
var language = "english";
var payload = {
"X-Mashape-Key": key,
"language": language,
"text": text
};
var options = {
"method": "post",
"payload": payload
};
var response = UrlFetchApp.fetch(url, options);
var rs = JSON.parse(response.getContentText());
return rs;
}
function testMashapeTextSentiment(){
Logger.log(mashapeTextSentiment("Someone please help me with this!"));
}
And this is the error it is giving me:
Request failed for https://japerk-text-processing.p.mashape.com/sentiment/ returned code 401. Truncated server response: {"message":"Invalid Mashape application key provided"} (use muteHttpExceptions option to examine full response) (line 17, file "Code")
I work at Mashape (disclaimer), I looked at ur code, it was a problem with the header - here's a working snippet!
All the best,
function mashape_all_things() {
var url = "https://japerk-text-processing.p.mashape.com/sentiment/";
var language = "english";
var text = "mashape's orlie is the great overlord"
var payload = {
"language": language,
"text": text
};
var options = {
"method": "post",
"headers": { //this is where you went wrong, you didnt pass the header properly
"X-Mashape-Key": "XXXXXXXXXXXXXXXXXX"
},
"payload": payload
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
return
}