YouTube Search Node.js with Google API - javascript

I am trying to do a YouTube search with the Google APIs within Node.
I am using this as somewhat of a tutorial:
https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client
I have some of the basics working:
var google = require('googleapis');
var YOUTUBE_API_KEY = "--YOUR_API_KEY";
var youtube = google.youtube('v3');
var requests = youtube.search.list({part:'snippet', q: 'cats', maxResults: 10});
When I call this I get this message:
Error: Daily limit for Unauthenticated Used Exceeded.
Now, this is obviously because I'm not using my API key. However, I cannot find any resource out there that shows you how the API key is used for Node.
Anything I find tells me to do something like this:
var YOUTUBE_CLIENT_KEY = '';
var CLIENT_SECRET = '';
var REDIRECT_URL = '/';
var OAuth2 = google.auth.OAuth2;
var oauth2Client = new OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL);
google.options({auth: oauth2Client});
Followed by my "youtube.search.list...".
The issue with this approach is I have NO idea where to get:
CLIENT_ID
CLIENT_SECRET
REDIRECT_URL
I cannot find any of these anywhere online. I have tried to just follow Javascript tutorials, since Node obviously uses Javascript, although it always requires the oAuth2... which requires the three things above.
Any helps/hints?

You should input api key in the auth parameter. This is the right way of doing it as per the https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client sample docs.
var google = require('googleapis');
var youtube = google.youtube({
version: 'v3',
auth: "your-api-key"
});
youtube.search.list({
part: 'snippet',
q: 'your search query'
}, function (err, data) {
if (err) {
console.error('Error: ' + err);
}
if (data) {
console.log(data)
}
});
Thanks

It took me a while to find this point but I am a beginner on node.js and googleapis, so if someone else would like to expand this answer they can.
I believe to set simply using the Simple API key, just warning that you should only keep this key on the server side. Never give this key out, or it can be abused!
var googleapis = require('googleapis');
googleapis.client.setApiKey('YOUR API KEY');
Found this via https://developers.google.com/api-client-library/javascript/features/authentication
under Simple access using the API key

Related

Accessing a private Google sheet with a google cloud service account

I have a private Google Spreadsheet and I’m trying to access it programmatically using Google Visualization/Google Charts. I've created the service account, and I have tried using the google-auth-library and googleapis npm packages to create an access token that I can then use to access the spreadsheet. But, when I try to use that access token to read from the spreadsheet, the request fails with HTTP code 401 (Unauthorized). What do I need to do in order to make this work?
This is my code:
const { auth } = require('google-auth-library');
const keys = require('./jwt.keys.json');
const id = '{Spreadsheet ID}';
const sheetId = '{Sheet ID}';
const query = "{Query}";
async function getClient(){
const client = auth.fromJSON(keys);
client.scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
console.log(client);
return client;
}
async function main(){
const client = await getClient();
const token = await client.getAccessToken();
console.log(token);
console.log(token.token);
const url = `https://docs.google.com/spreadsheets/d/${id}/gviz/tq?tqx=out:csv&tq=${encodeURIComponent(query)}&access_token=${token.token}#gid=${sheetId}`;
const res = await client.request({url});
console.log(res);
}
main().catch(console.error);
When I saw your script, I thought that it is required modifying the scope. I had got the same situation as you (the status code 401 using your endpoint). Unfortunately, it seems that your endpoint cannot be used using the scope of https://www.googleapis.com/auth/spreadsheets.readonly. So, for example, how about changing it as follows, and testing it again?
From:
https://www.googleapis.com/auth/spreadsheets.readonly
To:
https://www.googleapis.com/auth/spreadsheets
or
https://www.googleapis.com/auth/drive.readonly
Note:
When I tested your endpoint using the modified scope, I confirmed that no error occurred. But if you tested it and when an error occurs, please check other part, again.

GitHub API (Octokat.js): Cannot get Projects

I'm trying to access projects of a repository through GitHub API using Octokat.js.
The API guide says I need to use preview header, which I am using:
https://developer.github.com/v3/projects/
I'm getting error for property fetchAll of undefined (= projects).
I'm not sure what I'm doing wrong here - does anybody have an experience with this?
var Octokat = require('octokat')
var octo = new Octokat({
// put your own token here
token: 'XXX',
acceptHeader: 'application/vnd.github.inertia-preview+json'
})
octo.repos('YYY', 'ZZZ').projects.fetchAll((e, val) => {
this.projectsList = val
})
OK, turns out the API preview isn't implemented in the library yet.
https://github.com/philschatz/octokat.js/issues/144

How to get accessToken for firebase 3 using javascript

I need to make a shallow rest call using javascript with firebases REST Api, in the past version I needed to pass the access token like this:
var authKey = ref.getAuth().token;
var s = firebaseUrl + '/.json?shallow=true&auth=' + authKey;
$http.get(s)
How do I do this now with firebase 3?
firebase.auth().signInWithEmailAndPassword(u, p).then(function(result){
result.getToken().then(function(token){
$rootScope.userLoginToken = token;
});
});
The access token is no longer available in the authData when you're using version 3.x of the SDK. But you can get is when the user gets authenticated with.
var auth = firebase.auth();
var provider = new firebase.auth.GoogleAuthProvider();
auth.signInWithPopup(provider).then(function(result) {
var accessToken = result.credential.accessToken;
});
For this and a lot more information that is relevant when migrating your web app, see the upgrade guide for web apps (where I copied the code from).

How to properly generate Facebook Graph API App Secret Proof in Javascript

I am making a server side Facebook Graph API call to the all_mutual_friends edge: https://developers.facebook.com/docs/graph-api/reference/user-context/all_mutual_friends/
The call works when the two users are friends, but returns no useful data when they users aren't friends. According to the docs, this is because I must sign the call with the appsecret_proof parameter. No matter what I try, I am not able to successfully pass this parameter. I am using jsrsasign running on Parse. I have tried every configuration of using the access token as the message and my appSecret as the key, and vice versa. I have also tried multiple combinations of utf8 and hex. Every time I receive the error: invalid appsecret_proof provided in the API argument
Code:
var Signer = require("cloud/vendor/jsrsasign/lib/jsrsasign.js");
var userId = request.params.userId;
var accessToken = request.params.accessToken;
var appSecret = "redactedStringPastedFromFacebook";
var signer = new Signer.Mac({alg: "hmacsha256", pass: appSecret});
var appSecretString = signer.doFinalString(accessToken);
var appSecretHex = signer.doFinalHex(accessToken);
var graphRequestURL = "https://graph.facebook.com/v2.5/" + userId;
var fields = "?fields=context.fields(all_mutual_friends.fields(name,picture.width(200).height(200)))";
//var authorization = "&access_token=" + accessToken; //this works, but only for existing friends
var authorization = "&access_token=" + accessToken + "&appsecret_proof=" + appSecretHex;
return Parse.Cloud.httpRequest({
url: graphRequestURL + fields + authorization,
method: "GET",
})
Most examples I have seen are in PHP or Python and the crypto routines are a bit more clear. This works in that both appSecretString and appSecretHex don't throw errors and look reasonable, however the values are always rejected by Facebook.
Notes:
I have triple checked the App Secret value provided by Facebook
I have been approved by Facebook to use the all_mutual_friends feature, which is a requirement for this particular call
I am using Parse, which isn't Node, and can't use NPM modules that have external dependencies, which is why I am using jsrsasign. I also tried using CryptoJS directly, but it is no longer maintained and doesn't have proper module support and jsrsasign seems to wrap it anyway.
Here it is:
import CryptoJS from 'crypto-js';
const accessToken = <your_page_access_token>;
const clientSecret = <your_app_client_secret>;
const appsecretProof = CryptoJS.HmacSHA256(accessToken, clientSecret).toString(CryptoJS.enc.Hex);

Error making listNotebooks request using Evernote's Javascript SDK

I am creating a Cordova/Phonegap mobile app using the Ionic framework. I'm using Evernote's Javascript SDK and successfully got the OAuth process working.
I'm stuck at the very last step. I am trying to list my notebooks and keep generating an error. Everything seems to be working fine up until this point:
noteStore.listNotebooks(authTokenEvernote, function (notebooks)
At that point, I get an error that reads "{"position":0,"totalSize":0}". I've looked all over the forum and can't figure out what it means, or how to fix it.
Here is my code.
// authTokenEvernote can now be used to send request to the Evernote Cloud API
console.log('got access token:', authTokenEvernote)
console.log('got notestore url:', noteStoreURL)
// Here, we connect to the Evernote Cloud API and get a list of all of the
// notebooks in the authenticated user's account:
var noteStoreTransport = new Thrift.BinaryHttpTransport("noteStoreURL");
var noteStoreProtocol = new Thrift.BinaryProtocol(noteStoreTransport);
var noteStore = new NoteStoreClient(noteStoreProtocol);
noteStore.listNotebooks(authTokenEvernote, function (notebooks) {
console.log('success!! : ');
console.log(notebooks);
}, function onerror(error) {
console.log('error:')
console.log(error);
});
};
The listNotebooks method (like most Evernote methods) returns a err object first, then the object containing the notebooks.
Here is an example of how the listNotebooks method could be called:
var notebooks = noteStore.listNotebooks(function(err, notebooks) {
console.log("Found " + notebooks.length + " notebooks:");
for (var i in notebooks) {
console.log(" * " + notebooks[i].name);
}
console.log(notebooks)
});

Categories