Set Up Authentication
- Calendly uses OAuth 2.0 for authentication. You will need to obtain a personal access token or execute an OAuth handshake to interact with Calendly's API.
- To proceed, ensure you have a personal access token ready for use. You can generate this token from Calendly's developer portal. Remember, keep your token secure and do not expose it publicly.
Initialize a Node.js Project
- Create a new directory for your project and navigate into it. Use the following command to create a new `package.json` file.
npm init -y
- Install necessary packages. You'll need `axios` for making HTTP requests and `dotenv` for loading environment variables.
npm install axios dotenv
Create .env File
- Create a `.env` file in your project root to store your sensitive credentials. Add your Calendly access token here.
CALENDLY_ACCESS_TOKEN=your_access_token_here
Set Up Axios Instance with Authentication
- Create a new file named `apiClient.js`. This will handle all your API requests and manage authentication headers.
require('dotenv').config();
const axios = require('axios');
const apiClient = axios.create({
baseURL: 'https://api.calendly.com',
headers: {
Authorization: `Bearer ${process.env.CALENDLY_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
});
module.exports = apiClient;
Fetch Scheduled Events
- Create `getEvents.js` to fetch scheduled events using the Calendly API.
const apiClient = require('./apiClient');
async function getScheduledEvents() {
try {
const response = await apiClient.get('/scheduled_events');
return response.data;
} catch (error) {
console.error('Error fetching scheduled events:', error);
}
}
module.exports = getScheduledEvents;
Cancel an Event
- Implement functionality to cancel an existing scheduled event. Create a file named `cancelEvent.js` and add the following code.
const apiClient = require('./apiClient');
async function cancelEvent(eventUri) {
try {
const response = await apiClient.post(`${eventUri}/cancellation`, {
reason: 'The reason for cancellation'
});
return response.data;
} catch (error) {
console.error('Error cancelling event:', error);
}
}
module.exports = cancelEvent;
Integrate with Your Application
- In your main application file, e.g., `app.js`, you can now call these functions as required by your business logic.
const getScheduledEvents = require('./getEvents');
const cancelEvent = require('./cancelEvent');
(async () => {
const events = await getScheduledEvents();
console.log('Scheduled Events:', events);
// Example of cancelling an event using its URI
if (events.length > 0) {
const eventUri = events[0].uri; // Get the URI of the first event
await cancelEvent(eventUri);
console.log('Event cancelled successfully');
}
})();
- With the functions properly set up, you can now manage your Calendly scheduling events programmatically from your Node.js application.
- For additional functionalities, you can explore the full Calendly API documentation and integrate other endpoints similarly.