Accessing Google Calendar API from Node server

Stretch0 picture Stretch0 · Jul 7, 2017 · Viewed 9.1k times · Source

For some reason, I am having a really hard time accessing Google calendar.

I want to be able to add and remove events in a calendar from my Node.js server.

I am finding really conflicting information from the documents.

I followed - https://developers.google.com/identity/protocols/OAuth2ServiceAccount which gives a good guide on how to get an acccess token but then at the end it appears it is only for accessing Drive.

I then followed Google Calendar API v3 Access Not Configured which states you only need an API key but this appears as though it is all done from client side so maybe it's different?

I looked at https://developers.google.com/google-apps/calendar/quickstart/nodejs as well but that seems very complicated just to make a simple API call to a calendar. The sample code references files which isn't clear where they come from or how to structure them. E.g. var TOKEN_PATH = TOKEN_DIR + 'calendar-nodejs-quickstart.json';

I simple guide on how to achieve this would be hugely appreciated.

Thanks

Answer

ZuzEL picture ZuzEL · Oct 27, 2017

I was in the same situation as you. Google does not have documentation for server-to-server authentication for nodejs client API. Ridiculous. Finally I found the solution here. Basically you need a service account key (JSON file usually) and google.auth.JWT server-to-server OAuth 2.0 client.

let google = require('googleapis');
let privatekey = require("./privatekey.json");
// configure a JWT auth client
let jwtClient = new google.auth.JWT(
       privatekey.client_email,
       null,
       privatekey.private_key,
       ['https://www.googleapis.com/auth/calendar']);
//authenticate request
jwtClient.authorize(function (err, tokens) {
 if (err) {
   console.log(err);
   return;
 } else {
   console.log("Successfully connected!");
 }
});

Now just call calendar API like that:

let calendar = google.calendar('v3');
calendar.events.list({
   auth: jwtClient,
   calendarId: 'primary'//whatever
}, function (err, response) {

});