Udemy API HTTP Authorization - javascript

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);
}

Related

How to use curl with superagent/fetch in javascript

I am trying to wire up my app to an external api. The external api's documentation says to make the call using curl:
curl "https://wordsapiv1.p.mashape.com/words/soliloquy"
-H "X-Mashape-Key: <required>"
My app is built with JS/React - I am unfamiliar with the above syntax. I am trying to figure out how to write this using superagent (or, if necessary, fetch).
This is what I have so far from following some other SO answers but I have no idea how to incorporate: -H "X-Mashape-Key: <required>"
My api key is stored in a .env file.
require('dotenv').config
console.log(process.env)
const request = require('superagent')
const url = 'https://wordsapiv1.p.mashape.com/words/'
//dictionary
export function getDictionaryDefinition(word) {
return request.get(`${url}/dog`).then((response) => {
console.log(response)
})
}
I highly recommend getting familiar with the basics of curl. It's worth knowing and it's everywhere. you can find nice cheat sheets here and here.
-H in curl represent a header, so in your case you'll need to add that to your request, e.g.
request.get(`${url}/dog`)
.set('X-Mashape-Key', API_KEY)
.then((response) => {...
or in fetch:
fetch("https://wordsapiv1.p.mashape.com/words/soliloquy", {
headers: {
"X-Mashape-Key": API_KEY
}
})
as a bonus, I found a nice project that "translates" curl to fetch: https://kigiri.github.io/fetch/

Question regarding Google Apps Script oAuth2 Third Party Authentification Code

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;

How to convert a cURL request into a Google Apps Script UrlFetchApp

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 + '"'
}};

What headers to include in a UrlFetch / UrlFetchApp request when given a user ID?

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!

Getting UNAUTHORISED ERROR 401 - Sendgrid API

I am trying to perform actions on sendgrid lists via their API.
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#List-All-Lists-GET
I'm using this to set up my code however I'm getting Error 401 UNAUTHORISED when performing the request via $http in my Angular app.
I tried making the same request in Python and that seemed to working fine though.
var head = {'Authorization': 'Bearer SG.PE-XXXXXXXXXXXXXXXXXXXXXX'};
var sgUrl = "https://api.sendgrid.com/v3/contactdb/lists";
self.$http({
method : "GET",
url : sgUrl,
headers : head,
}).then(function mySuccess(response) {
alert(1);
}, function myError(response) {
alert(0);
});
Thanks!

Categories