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!