I'm aware this is probably basic stuff.
I've read a lot of the other questions on here around converting cURL into a Google Apps Script UrlFetchApp request however, I'm unable to get it to work. I'm a marketer, not a developer, so I have limited knowledge of Javascript but I'm usually able to manipulate reference scripts for my own needs. This one just won't work for me.
All I get is "Authentication has failed" as a response.
My current code is:
function wisepopsData() {
var API_KEY = 'APIKEYHERE';
var root = 'https://app.wisepops.com/api1/wisepops';
var params = {
'headers': {
'Authorization': 'WISEPOPS-API ' + Utilities.Base64Encode(API_KEY)
}
};
var response = UrlFetchApp.fetch(root, params);
var data = response.getContentText();
var json = JSON.parse(data);
Logger.log(json);
}
The documentation I'm using is below. I'm trying to implement the performance data part --> https://support.wisepops.com/en/articles/572165-wisepops-api-basics#performance-data-on-your-wisepops
The part I can't get my head around is 'Authorization: WISEPOPS-API key="YOUR_API_KEY_HERE"'. I've tried lots of combinations in the header of the request to get this bit to work and still nothing.
Try changing params variable intialization.
something like :
var params = {
'headers': {
'Authorization': 'WISEPOPS-API key="' + API_KEY + '"'
}};
Related
this is my first time posting a question to stack overflow since I have an issue I cant get past.
What I am trying to do:
I am trying to extract data of my car from the "Mercedes me" platform. It's a pure hobby project.
"Mercedes me" has an API with oAuth2 verification.
I am trying to realize this in Google Sheets since I want to do calculations with the data retrieved.
Hence I started coding in Apps Script.
I am able to exchange an Authentification Code with a Token and then get data from the platform using the following code:
var options = {
headers : { Authorization: 'Basic '+ Utilities.base64Encode('Client ID:Client Secret')},
method : 'post',
'content-type' : 'application/x-www-form-urlencoded',
muteHttpExceptions : false,
}
var authorization_code = 'TGVWD9pNif1wuDBYa6fFPn4QHNW9h6_f2-kxL34V'
var authUrl = 'https://id.mercedes-benz.com/as/token.oauth2?grant_type=authorization_code&code='+authorization_code+'&redirect_uri=https://localhost/';
var response = UrlFetchApp.fetch(authUrl, options);
var data = JSON.parse(response);
var token = data.access_token
'Logger.log(token);'
var options = {
headers : { Authorization: `Bearer ${token}`},
accept : 'application/json'
}
var response = UrlFetchApp.fetch('https://api.mercedes-benz.com/vehicledata/v2/vehicles/<vehicle identification number>/resources/', options);
'var jsonObject = JSON.parse(response.getContentText()); '
'var jsonObject = JSON.stringify(response);'
Logger.log(response);
So this is not the issue. The issue is that currently I need to manually insert the Authorization Code (as you can see in the code snippet above) which will then be exchanged with the Token by my script. The goal would be to generate the Authorization Code automatically.
I have created an authorization URL which will give me the Authorization Code when entered and opened in the Browser.
However, when I try to achieve the same in Apps Script via UrlFetchApp it will send me back some unusable html code instead of an Authorization Code.
function Authentification() {
var url = 'https://id.mercedes-benz.com/as/authorization.oauth2?response_type=code&client_id=a9f67f5f-cb2b-413b-9ea5-78df02b668a1&redirect_uri=https://localhost/&scope=mb:vehicle:mbdata:payasyoudrive&state=1000';
var options = {
muteHttpExceptions : false, //theoretisch nicht notwendig
followRedirects : true, //theoretisch nicht notwendig
method : 'get', //theoretisch nicht notwendig
}
var response = UrlFetchApp.fetch(url, options);
var json = response.getHeaders;
var data = JSON.stringify(json);
Logger.log(response)
}
Result is some html like this:
<!DOCTYPE html><html lang=en xmlns=http://www.w3.org/1999/xhtml><head><meta charset=utf-8><m
But what I am trying is to get a redirect Url like this (including the Authorization Code):
https://localhost/?code=DXPzKdV58t3rWlpuVmD3XT35BbL__n0auuAxL34V&state=1000
My assumption is, the problem is that when the link is opened by Apps Script's URLFetchApp it is never asked to enter my "Mercedes me" login credentials. Most likely I am not seing a basic OAuth logic here. Would really appreciate your help. Thanks a lot in advance.
Best Regards,
Chris
The solution came to my mind in my sleep :-D
I deployed the whole thing as a webapp and used the webapp-link as the redirect uri.
After this I was able to extract the authorization code from the url with the following code:
function doGet(e) {
var param = e.queryString;
param = e.parameter;
var code = param.code;
I'm having trouble using Google Apps to interact with a management software called Kissflow.
function fun2() {
var id = "yyy";
var apisecretkey = "xxx";
var url ='https://'+id+'.kissflow.com/api/1/verify';
var options = {
method: 'post',
headers : {"Authorization" : " Basic " + Utilities.base64Encode(id + ":" + apisecretkey)},
payload: {
"grant_type": "client_credentials",
"scope": "basic+user"
},
muteHttpExceptions: true
};
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
}
I would like to run this simple example of the API documentation, the goal is for me to be able to send data to the software through my interactions in a spreadsheet, for example. If you can help me in this I will be very grateful, I am new with API's :)
The following error appears: SyntaxError: unexpected token <in JSON at position 0 (line 30, file "Code") I don't know if I'm using this function correctly.
Kissflow API Documentation
JSON.parse(UrlFetchApp.fetch(url, options).getContentText())
Remove JSON.parse() from above line and output the response on your console using Logger.log() or to your browser log using console.log() and see the result. If there are errors it'll show more user friendly error message.
While I'm not familiar with the API, I suspect the issue is related to this line:
var response = JSON.parse(UrlFetchApp.fetch(url, options).getContentText());
You're fetching the response (which is probably JSON), then getting the content text of that response, then trying to parse that text as if it were JSON.
So (solution 1) if you set your response variable equal to
var response = UrlFetchApp.fetch(url, options).getContentText();
and try printing that variable to the console, you may find you have something you can work with.
Alternatively (solution 2), you might try:
var response = JSON.parse(UrlFetchApp.fetch(url, options));
if you'd rather have a JavaScript object to work with instead of a string (and assuming the .fetch method you're calling does indeed provide a JSON-formatted response.)
I've recently gotten credentials to pull from this API (CareerOneStop.org) and they sent me credentials that include an API token and a user ID. I have to admit that I'm a newbie when it comes to APIs, but I have used the Google Apps Script UrlFetchApp method to successfully make a GET request from an API that only requires a secret token.
For example, this JavaScript successfully calls the Udemy API:
function callUdemyInstructorAPI () {
var baseUrl = 'https://www.udemy.com/instructor-api/v1/';
var url = baseUrl + 'taught-courses/courses/?fields%5Bcourse%5D=#all&ordering=is_published';
var params = {
"method" : "GET",
"headers" : {
'Authorization' : 'bearer authToken',
}
};
var response = UrlFetchApp.fetch(url, params);
var parsedResponse = JSON.parse(response.getContentText());
}
However, the particular CareerOneStop.org API issues users an ID also, and I'm having a hard time figuring out how to write a request function that integrates it.
It looks like someone had a somewhat similar question on Stackoverflow, but they needed to provide a username and password, and I'm not sure that this ID / token authentication combination has the same needs.
Using what I've found in other places, I've built this function, but I get a 401 return:
function apiTest(){
var url = 'https://api.careeronestop.org/v1/occupation/I3ojbDKR1o97Veh/nurse/Y/0/10?datasettype=occ'; // this URL works, and you'll see that the user ID they give is part of the URL after occupation/
var token = "secretToken";
var headers =
{
Authorization : "Bearer " + token
}
var options =
{
"method" : "get",
"headers": headers
};
var result = UrlFetchApp.fetch(url, options);
var state = result.getContentText();
}
If you can give me any tips on formatting this API request, I'd be very grateful. I'n not sure what I need to do here...
Thanks in advance!
Hi I'm Learning API and I want to do a project with the the API of Udemy. Reading the documentation I see these example
curl --user {YOUR_CLIENT_ID}:{YOUR_CLIENT_SECRET} https://www.udemy.com/api-2.0/courses
curl -H "Authorization: Basic {BASE64_ENCODED(CLIENT_ID:CLIENT_SECRET)}" https://www.udemy.com/api-2.0/courses
But I don't know how to translate that into my code using superagent , right know I have this
const request = superagent
request.get("https://www.udemy.com/api-2.0/courses")
.set({myClientId}, {myClient_Secret})
.then(function(serverResult){
console.log(serverResult)})
But still appear in console
GET https://www.udemy.com/api-2.0/courses 403 (Forbidden)
In case this is helpful, this is a basic function that calls the Udemy Instructor API from Google Apps Script (GAS). GAS provides the UrlFetchApp().fetch() method. This is proprietary to Apps Script, but you still may find the structure of the header helpful.
function callUdemyInstructorAPI () {
var baseUrl = 'https://www.udemy.com/instructor-api/v1/';
var url = baseUrl + 'taught-courses/courses/?apiOptionsHere';
var params = {
"method" : "GET",
"headers" : {
'Authorization' : 'bearer mySecretUdemyAPIToken',
}
};
var response = UrlFetchApp.fetch(url, params);
}
My overall goal is the following:
-> Get data from fabric.io (=crashlytics) into a geckoboard dashboard.
To my knowledge there is no API on crashlytics/fabric side, so I had the following idea:
Write a script in nodejs (because I know node js a bit, I'm no expert though) that would:
Open the html page where the data I want is
Find my data using htmlparser
Save that data into a google sheet
Make geckoboard read the google sheet and display the data
Step 4 is done already and I'm working on step 1 now.
Unfortunately I'm having a problem as the page is not publicly accessible, I need to authenticate using my user account.
I've reused some code that works just fine when doing GET/POST/PUT on some other websites' REST api, but it doesn't seem to work here as fabric is redirecting me to the login page.
However when I search the web for node auth, I find modules for people to create a server that will handle authentication, whereas I'm trying to use node to login to a website.
It's well possible that what I'm trying to achieve or the way I'm trying to do it don't make sense at all. But as I'm not skilled enough to realise that, I'd be happy if someone could confirm it to me. At least I'd know I'm looking into the wrong direction ;-)
Thanks for reading me
Here is my code:
var fs = require('fs');
var https = require('https');
var creds = require('./config/credentials.js');
var date = new Date();
var htmlpage = "";
var authorizationHeader = "Basic " + new Buffer(creds.login + ":" + creds.pwd).toString("base64");
var get_options = {
hostname: "fabric.io",
path: "/my-company-account/ios/apps/app.identifier/answers/stability",
method: "GET",
port: 443,
headers: {
"content-type": "application/json",
"Authorization": authorizationHeader
}
};
var get_req = https.request(get_options, function(res){
res.setEncoding('utf8');
res.on('data', function(chunk){
htmlpage += chunk;
}); // end res.on 'data'
res.on('end', function(){
console.log(htmlpage);
//tmp debug
fs.writeFile('./logs/ac-ios_' + date.getTime() + '.html', htmlpage, function(err){
if (err) {
console.log(err);
}
}); // end write html file
/*var parser = new htmlparser.Parser(handler);
parser.parseComplete(htmlpage);*/
}); // end res.on 'end'
}); // end https.request
get_req.on("error", function(err){
console.log(err);
});
get_req.end();
Which gives me the following html:
<html>
<body>You are being redirected.</body>
</html>