Google Spreadsheet Creation - Node.js - node.js

I am trying to create new google spreadsheet using the google spreadsheet api using node.js
I have managed to get the Google OAuth 2.0 working, where I am getting the access tokens for the clients.
Now on searching the Google API docs there are example using the gData client library but nothing giving me pointers to node.js
Here are my findings for creating a new google spreadhseet
Upload a spreadsheet manually OR
Use a resumable upload link
There is not much information on the resumable upload link.
I can see the HTTP Post Request and Response but I do not understand how to construct the post request in node.js
EDIT--
I am reading Google Apps Platform

Here is how to do it with the create method of the Google Sheets API (currently v4).
This code examples does not use any 3rd party libraries, it uses googleapis: Google API's official Node.js client
const google = require('googleapis');
const sheets = google.sheets('v4');
// authenticate, and store that authentication, in this example
// it is stored in a variable called `auth`. I am using JWT
// authentication, but you can use the any form of authentication
const auth = new google.auth.JWT(
key.client_email,
null,
key.private_key,
['https://www.googleapis.com/auth/spreadsheets'], // make sure that your auth scope includes `spreadsheets`, `drive` or `drive.file`
null
);
sheets.spreadsheets.create({
auth: auth,
resource: {
properties: {
title: 'Title of your new spreadsheet'
}
}
}, (err, response) => {
if (err) {
console.log(`The API returned an error: ${err}`);
return;
}
console.log('Created a new spreadsheet:')
console.log(response);
});

If all you want to know is how to construct post request, then check this example
http://nodejs.org/api/http.html#http_http_request_options_callback

Checkout
https://github.com/EastCloud/node-spreadsheets/
EastCloud has written a friendly-ish wrapper around the Google Docs/Drive API

If you are new and want to get and add data to Google spreadsheets, please refer below link to get step-by-step guide.
https://www.twilio.com/blog/2017/03/google-spreadsheets-and-javascriptnode-js.html
I was tested same in recent nodejs project

Related

nodejs - Getting 401 error trying to download docs revisions with Google Drive API export links

I need to download all the revisions of a google doc with the Drive API using nodejs but I don't understand how to authorize the request for the export links. Once I get the export link for each revision I call:
var options = {
url: 'https://docs.google.com/feeds/download/documents/export/Export?id=1DRl6rbcVuuLVyb_WlhBLiYiCByWcS2bKGlLIsn7E8_8&revision=1&exportFormat=txt', //example link
method: 'GET',
headers: {
Authorization: `Bearer ${jwToken}`,
},
}
request(options).pipe(fs.createWriteStream(mydownloadfilename));
where the "jwToken" is the token I use to get the revisions list so I guess it should be still valid. However, with this I get the 401-Unauthorized page. What am I doing wrong?
Thanks
According to the Drive API v3 documentation:
Revisions for Google Docs, Sheets, and Slides can't be downloaded.
So essentially, if the actual revision you want to retrieve is the file itself, then the method above is the correct one.
As for the authorization part, you will need to perform the Node.js Quickstart from here and follow the steps explained there.
Since you want to export the file, you will just need to modify the code and add this part:
function downloadDoc() {
var fileId = 'ID_OF_THE_DOC';
var dest = fs.createWriteStream('DESTINATION_OF_THE_OUTPUT_STREAM');
drive.files.export({
fileId: fileId,
mimeType: 'application/vnd.google-apps.document'
})
.on('end', function () {
console.log('Done');
})
.on('error', function (err) {
console.log('Error during download', err);
})
.pipe(dest);
}
Reference
Drive API v3 - Manage Revisions;
Drive API v3 - Files:export;
Drive API v3 - Quickstart;
Drive API v3 - Download a document.
I am facing this same problem. The solution is to use
OAUTH2 authorization for a user that has Edit or Owner permissions for a file
Get an access token that expires quickly
call the V2 URI (V3 does not work) for the file/rev to get "export links" 3) Call the correct export link for your format type
then you will get a randomized temporary redirect link from Google that you can then call to get the binary stream.
This is a great starting point for C# .NET -- windows oauth console app, if you want working code to do steps 1 and 2. I posted a working v2 code function here that you can put into the console app example.

How to add Google Contact using Nodejs API or curl request

I want to add new contact details if it does not exist in my google contacts
I don't think Nodejs is supported in Google Contacts API. Use this guide of google contacts.
This document is intended for programmers who want to write client
applications that can interact with Google's contact lists. It
provides a series of examples of basic API interactions. These
examples come in various forms, including raw XML/HTTP requests,
Java, .NET and Python source code.
Also, you can run the sample codes using these protocols.
If you're using a UNIX system and you want to try the examples in this
document without writing any code, you may find the UNIX command-line
utilities curl or wget useful; for more
information, see the manual pages for those utilities.
Use https://www.npmjs.com/package/google-contacts-crud npm to read and add google contacts.
Google's official API for NodeJS doesn't use Contacts API, only the People API.
You can connect with Contacts API using the official googleapis library if you're already using it for other purposes by sending a request to the Contacts API after creating the auth client.
Given that you already have the access token of the user (e.g. if you generated it using Passport, here's the code:
const {google} = require("googleapis");
const authObj = new google.auth.OAuth2({
access_type: 'offline',
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
});
Refresh access token automatically before it expires
authObj.on('tokens', (tokens) => {
const access_token = tokens.access_token
if (tokens.refresh_token){
this.myTokens.refreshToken = tokens.refresh_token
// save refresh token in the database if it exists
}
this.myTokens.accessToken = tokens.access_token
// save new access token (tokens.access_token)
}
authObj.setCredentials({
access_token:this.myTokens.accessToken,
refresh_token:this.myTokens.refreshToken,
});
Make the request to Contacts API:
authObj.request({
headers:{
"GData-Version":3.0
},
params:{
"alt":"json",
//"q":"OPTIONAL SEARCH QUERY",
//"startindex":0
"orderby":"lastmodified",
"sortorder":"descending",
},
url: "https://www.google.com/m8/feeds/contacts/default/full"
}).then( response => {
console.log(response); // extracted contacts
});

Sync contacts using Google Contacts API version 3.0 and NodeJS' Passport

I am using passport, and would like to use the Google Contacts API version 3.0 to sync Google contacts with my application (which would suddenly become 10 times more useful).
Has anybody done this? If so, do you have some example code? Is it even possible to use passport authentication to get it all working?
This comes in two parts, authorization, and then the actual request.
It is basically using OAuth2 protocol, where you redirect the client to google url with scopes(You must at least have https://www.google.com/m8/feeds in your scopes to be able to read and write contacts) and your client id/secret(get them by registering your app. Then google will redirect the user back with the access token on the URL.
You don't need to do this yourself, because there are different modules that already does this:
passport-google-oauth
This makes it easy and assuming you are already using passport, this probably what you want. It is written by the author of passportjs. Just follow the example in it for OAuth 2.0 strategy. Note that you need to you add the right scopes when you are calling passport.authenticate('google', ...). This module when it gets the token, it will get the user profile, so you have to have one of the 3 scopes below:
passport.authenticate('google', { scope: [ // One of the next three `auth` scopes are needed.
'https://www.googleapis.com/auth/userinfo.profile',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/plus.login',
'https://www.google.com/m8/feeds'
] }),
googleapis
This is module is officially supported by google and created by google employees. You can use it to authenticate, but sadly it doesn't support gData, which contains google contacts. You can check the example to see how you can get the token. You only need the m8/feeds scope with this module, no need for the other ones if you don't want to get the user profile.
gdata-js
This is a non-popular non-maintaining module, but it is more lightweight than the previous two modules. It might need a little polishing out of the box. I suggest also reading the source for understanding the api right.
Once you got the tokens, then you go for the slightly easier part, making the requests and getting the data.
If you read the docs, it's actually very easy. For example to get all contacts(almost all, it's paginated), you need to make a GET request to this url:
https://www.google.com/m8/feeds/contacts/default/full?alt=json&oauth_token=THE_ACCESS_TOKEN
Again there are many modules that can help you in this.
google-contacts
node-gdata
gdata-js Read the source to understand it's api. It's pretty easy actually:
var client = require('gdata-js')(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET);
client.setToken({ access_token: accessToken, refresh_token: refreshToken });
client.getFeed('https://www.google.com/m8/feeds/contacts/default/full', function (err, result) { ... });
Google's official API for NodeJS doesn't support Contacts API, only the People API.
You can connect with Contacts API using the official googleapis library if you're already using it for other purposes by sending a request to the Contacts API after creating the auth client.
Given that you already have the access token of the user (e.g. if you generated it using Passport, here's the code:
const {google} = require("googleapis");
const authObj = new google.auth.OAuth2({
access_type: 'offline',
clientId: process.env.GOOGLE_ID,
clientSecret: process.env.GOOGLE_SECRET,
});
Refresh access token automatically before it expires
authObj.on('tokens', (tokens) => {
const access_token = tokens.access_token
if (tokens.refresh_token){
this.myTokens.refreshToken = tokens.refresh_token
// save refresh token in the database if it exists
}
this.myTokens.accessToken = tokens.access_token
// save new access token (tokens.access_token)
}
authObj.setCredentials({
access_token:this.myTokens.accessToken,
refresh_token:this.myTokens.refreshToken,
});
Make the request to Contacts API (Google uses Gaxios for making the requests to their APIs although it's not documented officially in googleapis, so just be aware that they might change remove/change the request call in the future without documenting it)
authObj.request({
headers:{
"GData-Version":3.0
},
params:{
"alt":"json",
//"q":"OPTIONAL SEARCH QUERY",
//"startindex":0
"orderby":"lastmodified",
"sortorder":"descending",
},
url: "https://www.google.com/m8/feeds/contacts/default/full"
}).then( response => {
console.log(response); // extracted contacts
});

Authenticate JIRA REST API using OAuth with Node.JS

I'm building a client application in Node.js for creating new JIRA issues and I want to authenticate users using OAuth. The Atlassian docs are pretty bad for Jira and Oauth newcomers. So, I'm looking for a single example that describes exactly how to set up the JIRA application link, and the how to build a basic app in node that connects to Jira via OAuth. I'm not sure where else to look. (I'm using JIRA v6.0.4)
There is an example for Node.JS with OAuth in the Atlassian repo that Brian also mentioned. I think it is for the 2-legged authentication.
It needs a pre-negotiated consumer key already set up by you. Here is an example how to obtain a token you can save in your config file: https://developer.atlassian.com/jiradev/api-reference/jira-rest-apis/jira-rest-api-tutorials/jira-rest-api-example-oauth-authentication
Here's a blog describing node.js and jira authentication using Oauth
It is in an express framework. I paste some part of the code below.
var base_url = "YOUR_JIRA_BASE_URL"; //example https://test.atlassian.net
app.get('/jira', function(req, res) {
var oa = new OAuth(base_url + "/plugins/servlet/oauth/request-token", //request token
base_url + "/plugins/servlet/oauth/access-token", //access token
"mykey", //consumer key
"YOUR_PEM_FILE_CONTENT", //consumer secret, eg. fs.readFileSync('jira.pem', 'utf8')
'1.0', //OAuth version
"http://localhost:1337/jira/callback", //callback url
"RSA-SHA1");
oa.getOAuthRequestToken(function(error, oauthToken, oauthTokenSecret) {
if (error) {
console.log(error.data);
response.send('Error getting OAuth access token');
} else {
req.session.oa = oa;
req.session.oauth_token = oauthToken;
req.session.oauth_token_secret = oauthTokenSecret;
return res.redirect(base_url + "/plugins/servlet/oauth/authorize?oauth_token=" + oauthToken);
}
});
});
If anyone is confused about any part of the code, you can add comment to this answer.

Upload a photo to facebook album

I have a nodejs (+express + mongodb,gridstore) backend, and want to upload a photo to a facebook album.
I came across 2 methods. the first ( https://developers.facebook.com/blog/post/526/ ) needs to get the full url resource of my picture, which I don't have as it is data that I pull from gridstore,
and the second ( https://developers.facebook.com/docs/reference/api/album/ ) is very poorly documented, via the Graph API, where I can't figure out what my request should look like. (the form-data, what fields should it have, how to convert my data blob\stream from gridstore to it)
Here is what I currently have, and doesn't work:
facebook.uploadPhoto = function (token, albumId, photo, callback) {
var fb = fermata.json('https://graph.facebook.com/' + albumId);
fb.photos({access_token:token}).post({'Content-Type':"multipart/form-data"}, {source:{data:photo}}, callback);
};
Any help would be much appreciated
There is a good chance the file is not properly serialized. Fermata will take a node File buffer via data. Have you tried passing that instead?
fs.readFile("/path/to/photo.jpg", function (err, data) {
fermata.json("https://graph.facebook.com/graph/api").post({"Content-Type":"multipart/form-data"}, {fileField: {data:data, name:"", type:""} }, callback);
});
Adding your access token etc..
I solved this problem by using a simple POST to the facebook graph API using the poster module.
var options = {
uploadUrl: 'https://graph.facebook.com/'+user+'/photos?access_token='+accessToken,
method: 'POST',
fileId: 'source',
fields: {'message':''} // Additional fields according to graph API
};
var fileName = ''; // Local or remote url where to find the image
poster.post(fileName, options, function(err, data) {
if (err) {
//Something went wrong
} else {
// Everything ok
}
});
Honestly, I've got limited experience working with the Facebook graph API and mostly using PHP and Java.
Here is some streams that you might find helpful:
Upload Photo To Album with Facebook's Graph API
Facebook Graph API - upload photo using JavaScript
Basically, I recommend you punt a little in your implementation and code it in the following way:
Create a REST web service function call in Node.js to output a single image from gridstore using an internal UID.
Code your uploadToFacebook function to use an image URL that calls the REST web service function.
Basically, this would allow you to validate the image output by pointing your browser to the REST web service and avoid any blob\stream conversions inside your uploadToFacebook function. I'm assuming you store the image in gridstore vs. mongodb.
hope that helps...

Resources