Working with the Google Calendar API in node.js

04 Feb 2018 in Tech

To work through this post, you'll need a Google access token.

Start by installing the Google npm libraries that we'll need:

bash
npm install googleapis google-auth-library@^1.0.0 --save

Once we have our libraries, we need to configure our OAuth client to use the access token we obtained in the last post, then get an instance of the google calendar API:

javascript
var fs = require("fs");
var google = require("googleapis");
var googleAuth = require("google-auth-library");
var TOKEN_DIR =
(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE) +
"/.credentials/";
var TOKEN_PATH = TOKEN_DIR + "calendar-nodejs-quickstart.json";
const googleSecrets = JSON.parse(
fs.readFileSync("client_secret.json")
).installed;
var oauth2Client = new googleAuth.OAuth2Client(
googleSecrets.client_id,
googleSecrets.client_secret,
googleSecrets.redirect_uris[0]
);
const token = fs.readFileSync(TOKEN_PATH);
oauth2Client.setCredentials(JSON.parse(token));
var calendar = google.calendar("v3");

At this point, we can start making requests to the Google calendar API. The Google docs aren't great, but there is a pattern to them. If you read the API docs, you can work out the required method name e.g. CalendarList.list (which is a request to GET /users/me/calendarList) is exposed as calendar.calendarList.list(). Take the section title, make it camelCase and then call the operation you want to do. Any available parameters can be passed as the first parameter (as well as the oauth2 client to use). Here are some examples:

Listing available calendars

CalendarList.list becomes calendar.calendarList.list({"maxResults": 10}, callback) (options)

javascript
calendar.calendarList.list({ auth: oauth2Client }, function (err, resp) {
resp.data.items.forEach(function (cal) {
console.log(cal.summary + " - " + cal.id);
});
});

Listing events

To list events, you need to know the calendar ID you're working with. This can be found using the calendarList method above.

Events.list becomes calendar.events.list({"calendarId": id, "timeMin": "2018-02-11T00:00:00.000Z", "timeMax": "2018-02-11T23:59:59.000Z"}, callback) (options)

javascript
calendar.events.list(
{
auth: oauth2Client,
calendarId: "CALENDAR_ID",
timeMin: "2018-02-11T00:00:00.000Z",
timeMax: "2018-02-11T23:59:59.000Z",
},
function (err, response) {
if (err) {
console.log("The API returned an error: " + err);
return;
}
var events = response.data.items;
events.forEach(function (event) {
var start = event.start.dateTime || event.start.date;
console.log("%s - %s", start, event.summary);
});
}
);

At this point I had all the data I needed to continue building my application