|

|  How to Create and Manage Google Calendar Events Using Google Calendar API in Node.js

How to Create and Manage Google Calendar Events Using Google Calendar API in Node.js

October 31, 2024

Learn to create and manage Google Calendar events in Node.js using the Google Calendar API. Step-by-step guide for seamless event integration and automation.

How to Create and Manage Google Calendar Events Using Google Calendar API in Node.js

 

Install Google APIs Client Library for Node.js

 

Start by installing the Google APIs client library for Node.js. This library allows you to interact with Google services, including Google Calendar.

npm install googleapis

 

Set Up OAuth2 Client

 

To use the Google Calendar API, you need to authenticate and authorize with OAuth2.

  • Download your OAuth 2.0 credentials (client_id, client_secret) from the Google Developers Console.
  •  

  • Create a new file `credentials.json` and add your downloaded credentials there.

 

const { google } = require('googleapis');
const credentials = require('./credentials.json');

const { client_id, client_secret, redirect_uris } = credentials.web;
const oAuth2Client = new google.auth.OAuth2(client_id, client_secret, redirect_uris[0]);

 

Authenticate and Access Token

 

You need to generate an access token to interact with the calendar API. Here’s how you get the authorization URL and exchange the code for a token.

  • Access the scopes for Google Calendar API (e.g., 'https://www.googleapis.com/auth/calendar').
  •  

  • Generate an authorization URL for user consent and use the URL to authorize the application, then accept the code to get an access token.

 

const SCOPES = ['https://www.googleapis.com/auth/calendar'];
const authUrl = oAuth2Client.generateAuthUrl({
  access_type: 'offline',
  scope: SCOPES,
});

console.log('Authorize this app by visiting this url:', authUrl);

// After visiting the URL, you will get a code. Exchange this code for tokens:
async function getAccessToken(code) {
  const { tokens } = await oAuth2Client.getToken(code);
  oAuth2Client.setCredentials(tokens);
  console.log('Access Token and Refresh Token stored to oAuth2Client');
}

 

Create a Google Calendar Event

 

After obtaining your access token, you can move on to creating an event.

  • Define the event details such as summary, start time, end time, and optionally, attendees.
  •  

  • Use the calendar API to insert the event into the user's calendar.

 

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

const event = {
  summary: 'Project Meeting',
  location: '123 Business St, Business City',
  description: 'Discuss project details.',
  start: {
    dateTime: '2023-01-15T09:00:00-07:00',
    timeZone: 'America/Los_Angeles',
  },
  end: {
    dateTime: '2023-01-15T10:00:00-07:00',
    timeZone: 'America/Los_Angeles',
  },
  attendees: [{ email: 'attendee@example.com' }],
};

calendar.events.insert({
  auth: oAuth2Client,
  calendarId: 'primary',
  resource: event,
}, (err, event) => {
  if (err) {
    console.log('Error contacting the Calendar service:', err);
    return;
  }
  console.log('Event created:', event.data.htmlLink);
});

 

List Calendar Events

 

You can fetch and list calendar events to manage or view them.

  • Specify parameters such as max results, single events preference, and date range for the listing.
  •  

  • Use the calendar API to retrieve and print the events.

 

calendar.events.list({
  calendarId: 'primary',
  timeMin: (new Date()).toISOString(),
  maxResults: 10,
  singleEvents: true,
  orderBy: 'startTime',
}, (err, res) => {
  if (err) return console.log('The API returned an error:', err);

  const events = res.data.items;
  if (events.length) {
    console.log('Upcoming 10 events:');
    events.map((event, i) => {
      const start = event.start.dateTime || event.start.date;
      console.log(`${start} - ${event.summary}`);
    });
  } else {
    console.log('No upcoming events found.');
  }
});

 

Manage Events (Update or Delete)

 

Once you've created your events, you may need to update or delete them.

  • To update an event, fetch the event, modify the necessary fields, and then use `calendar.events.update()`.
  •  

  • To delete an event, use `calendar.events.delete()` with the event ID.

 

// Update an Event
calendar.events.update({
  calendarId: 'primary',
  eventId: 'your-event-id',
  resource: updatedEvent, // The event object with updated fields
}, (err, event) => {
  if (err) {
    console.log('There was an error updating the event:', err);
    return;
  }
  console.log('Event updated:', event.data.htmlLink);
});

// Delete an Event
calendar.events.delete({
  calendarId: 'primary',
  eventId: 'your-event-id',
}, (err) => {
  if (err) {
    console.log('There was an error deleting the event:', err);
    return;
  }
  console.log('Event deleted.');
});

 

Error Handling and Logging

 

It's important to implement proper error handling and logging to ensure smooth performance.

  • Wrap API calls in try-catch blocks or use promises to capture errors.
  •  

  • Log errors and responses to debug and monitor your application's performance.

 

try {
  const response = await calendar.events.insert({
    auth: oAuth2Client,
    calendarId: 'primary',
    resource: event,
  });
  console.log('Event created: %s', response.data.htmlLink);
} catch (error) {
  console.error('Error creating event:', error);
}

 

By following these steps and utilizing the detailed code examples, you'll be able to proficiently create and manage Google Calendar events using the Google Calendar API in Node.js. Happy coding!

Pre-order Friend AI Necklace

Pre-Order Friend Dev Kit

Open-source AI wearable
Build using the power of recall

Order Now

OMI AI PLATFORM
Remember Every Moment,
Talk to AI and Get Feedback

Omi Necklace

The #1 Open Source AI necklace: Experiment with how you capture and manage conversations.

Build and test with your own Omi Dev Kit 2.

Omi App

Fully Open-Source AI wearable app: build and use reminders, meeting summaries, task suggestions and more. All in one simple app.

Github →

Join the #1 open-source AI wearable community

Build faster and better with 3900+ community members on Omi Discord

Participate in hackathons to expand the Omi platform and win prizes

Participate in hackathons to expand the Omi platform and win prizes

Get cash bounties, free Omi devices and priority access by taking part in community activities

Join our Discord → 

OMI NECKLACE + OMI APP
First & only open-source AI wearable platform

a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded a person looks into the phone with an app for AI Necklace, looking at notes Friend AI Wearable recorded
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
online meeting with AI Wearable, showcasing how it works and helps online meeting with AI Wearable, showcasing how it works and helps
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded
App for Friend AI Necklace, showing notes and topics AI Necklace recorded App for Friend AI Necklace, showing notes and topics AI Necklace recorded

OMI NECKLACE: DEV KIT
Order your Omi Dev Kit 2 now and create your use cases

Omi Dev Kit 2

Endless customization

OMI Necklace

$69.99

Make your life more fun with your AI wearable clone. It gives you thoughts, personalized feedback and becomes your second brain to discuss your thoughts and feelings. Available on iOS and Android.

Your Omi will seamlessly sync with your existing omi persona, giving you a full clone of yourself – with limitless potential for use cases:

  • Real-time conversation transcription and processing;
  • Develop your own use cases for fun and productivity;
  • Hundreds of community apps to make use of your Omi Persona and conversations.

Learn more

Omi Dev Kit 2: build at a new level

Key Specs

OMI DEV KIT

OMI DEV KIT 2

Microphone

Yes

Yes

Battery

4 days (250mAH)

2 days (250mAH)

On-board memory (works without phone)

No

Yes

Speaker

No

Yes

Programmable button

No

Yes

Estimated Delivery 

-

1 week

What people say

“Helping with MEMORY,

COMMUNICATION

with business/life partner,

capturing IDEAS, and solving for

a hearing CHALLENGE."

Nathan Sudds

“I wish I had this device

last summer

to RECORD

A CONVERSATION."

Chris Y.

“Fixed my ADHD and

helped me stay

organized."

David Nigh

OMI NECKLACE: DEV KIT
Take your brain to the next level

LATEST NEWS
Follow and be first in the know

Latest news
FOLLOW AND BE FIRST IN THE KNOW

San Francisco

team@basedhardware.com
Title

Company

About

Careers

Invest
Title

Products

Omi Dev Kit 2

Openglass

Other

App marketplace

Affiliate

Privacy

Customizations

Discord

Docs

Help