Google Calendar API Integration Made Easy
Published: 2019-07-08 14:37:37

---
title: Google Calendar API Integration Made Easy
published: true
description: 
tags: 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/28lq1y1bc8tejkgx2exd.jpg
---

I recently struggled to integrate the Google Calendar API while trying to create an event listing for a website. While in retrospect most of it should have been easy but there were a few tricky configurations that were required. I wanted to share the steps I took to integrate a website with the Google Calendar API. We will use JWT authentication which is the most secure and flexible way to connect to a Google API. Keep in mind this type of connection is to connect to a Google that you manage, not a users Google account.

## Enable the Calendar API

First we need to setup the Google API and gather the various connection information that we will need in order to connect to it. To begin simply enable the calendar API.

1. The first step is to go to the [Google API Console](https://console.developers.google.com/apis/dashboard) and either select an existing project or create a new project.
1. Then select the "Enable APIS and Services" button
1. Type "Calendar" into the search box
1. Click on "Google Calendar API"
1. Click "Enable"

## Setup JWT Access

Next we need to create a JSON Web Token, commonly referred to as "JWT". This will provide us with the information that we need to programmatically access various Google API's in a secure context.

1. Go to the [Google API Console](https://console.developers.google.com/apis/dashboard) 
1. Choose "Credentials" from the left hand navigation
1. Click the "Create Credentials" button
1. Choose "Service account key"
1. This will download a JSON file to your computer. We will refer to this as the JWT JSON file throughout this blog post.

## Retrieve the Google Project Number

Now we need to retrieve the Google Project Number which will be required by the Google API.

1. Go to the [Google API Console](https://console.developers.google.com/apis/dashboard)c
1. In the top right of the screen click the three dot menu option next to your profile picture.
1. Click "Project Settings"
1. Copy the "Project Number" and paste it somewhere for safe keeping. We will refer to this as <project-number> throughout this blog post in code examples

## Setup the Google Calendar

Finally we need to configure the Google calendar and retrieve the ID. This was the tricky step as you have to give the JWT token access to you calendar as mentioned in steps 5-7 below.

1. Go to [Google Calendar](https://calendar.google.com/calendar/r)
1. On the left hand side hover over the calendar that you want to list events for and click the three dot menu icon
1. Click "Settings and sharing"
1. Scroll down and copy the "Calendar ID" and paste it somewhere for safe keeping. We will refer to this as <calendar-id> throughout this blog post in code examples.
1. Open up the JWT JSON file and copy the client email.
1. Go to the "share with specific people" section of the calendar and click "Add people"
1. Paste the client email and submit the dialog

## Setup Example Express Project

Now let's create a sample project using Node.JS with an Express server. Create a directory for your project and run the following commands:

```
npm init
npm install express --save
npm install googleapis --save
```

## Create Your Express Server

Finally we need to write code that will start up an express server to listen to requests, contact the Google Calendar API with our connection details that we retrieved above, and then reply with the result. Note that the constants defined at the start of the file need updated based upon the corresponding values we retrieved earlier. The <private-key> and <client-email> values both come from the JWT JSON file.

/index.js

```js
const express = require('express');
const { google } = require('googleapis');

const app = express();
const port = 3000;

const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly';
const GOOGLE_PRIVATE_KEY="<private-key>"
const GOOGLE_CLIENT_EMAIL = "<client-email>"
const GOOGLE_PROJECT_NUMBER = "<project-number>"
const GOOGLE_CALENDAR_ID = "<calendar-id>"

app.get('/', (req, res) => {
  const jwtClient = new google.auth.JWT(
    GOOGLE_CLIENT_EMAIL,
    null,
    GOOGLE_PRIVATE_KEY,
    SCOPES
  );

  const calendar = google.calendar({
    version: 'v3',
    project: GOOGLE_PROJECT_NUMBER,
    auth: jwtClient
  });

  calendar.events.list({
    calendarId: GOOGLE_CALENDAR_ID,
    timeMin: (new Date()).toISOString(),
    maxResults: 10,
    singleEvents: true,
    orderBy: 'startTime',
  }, (error, result) => {
    if (error) {
      res.send(JSON.stringify({ error: error }));
    } else {
      if (result.data.items.length) {
        res.send(JSON.stringify({ events: result.data.items }));
      } else {
        res.send(JSON.stringify({ message: 'No upcoming events found.' }));
      }
    }
  });
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));
```

Now run your server with `node index.js` and go to [localhost:3000](http://localhost:3000/) to see the result. Remember to move the private key and other constants into environment variables instead of committing them to source control. You should see the next 10 events that were added to the Google Calendar. This can be used to integrate a Google Calendar with an upcoming events feature on a website or could serve as a starting point for other features requiring a Google Calendar integration. Lastly the JWT authentication shown here can be used for a wide variety of Google APIs.