DEV Community

Cover image for Fetching Calendly API Events Using Express and Node.js
Eze Sugar 👩‍💻
Eze Sugar 👩‍💻

Posted on

Fetching Calendly API Events Using Express and Node.js

Introduction
In this article, we will explore how to fetch event data from the Calendly API and save it into a MongoDB database using an Express.js application. We will cover the entire process from setting up the project to performing CRUD operations to manage the data. Additionally, we will guide you on how to obtain your Calendly access token.

Prerequisites
Before we begin, ensure you have the following:

  • Node.js installed on your system
  • MongoDB installed or a MongoDB Atlas account
  • Basic understanding of JavaScript and Node.js
  • A Calendly account

Getting Your Calendly Access Token
To interact with the Calendly API, you'll need an access token. Follow these steps to obtain it:

Log in to Calendly:
Go to the Calendly login page and sign in to your account.

Navigate to the Integrations Page:
Click on your account in the top right corner, select "Integrations," and then click on "API and Webhooks."

Generate an Access Token:
Click "Get a token now," name your token, and click "Create token." Copy the generated token and keep it secure.

Store the Token Securely:
Create a .env file in your project directory and add your access token:

CALENDLY_ACCESS_TOKEN=your_calendly_access_token
MONGO_URI=your_mongodb_connection_string

Enter fullscreen mode Exit fullscreen mode

Setting Up the Project

  1. Initialize a New Node.js Project:
mkdir calendly-integration
cd calendly-integration
npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install Necessary Dependencies:
npm install express mongoose axios dotenv
Enter fullscreen mode Exit fullscreen mode
  1. Project Structure: Organize your project with the following structure:
calendly-integration/
├── controllers/
│   └── calendlyController.js
├── models/
│   └── Calendly.js
├── routes/
│   └── calendlyRoutes.js
├── .env
├── package.json
└── server.js
Enter fullscreen mode Exit fullscreen mode

Code Implementation

  1. Setting Up Server
// server.js
import express from 'express';
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import calendlyRoutes from './routes/calendlyRoutes.js';

dotenv.config();

const app = express();
app.use(express.json());

mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.error('MongoDB connection error:', err));

app.use('/api/calendly', calendlyRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Enter fullscreen mode Exit fullscreen mode
  1. Creating the Mongoose Model:
// models/Calendly.js
import mongoose from 'mongoose';

const calendlySchema = new mongoose.Schema({
  name: String,
  email: String,
  eventDetails: Object,
});

const Calendly = mongoose.model('Calendly', calendlySchema);

export default Calendly;
Enter fullscreen mode Exit fullscreen mode
  1. Creating the Route Handlers:
// controllers/calendlyController.js
import axios from 'axios';
import Calendly from '../models/Calendly.js';

export const createCalendly = async (req, res, next) => {
  try {
    const { name, email, ...otherEventDetails } = req.body;
    const existingUser = await Calendly.findOne({ email });

    let user;
    if (existingUser) {
      user = await existingUser.save();
    } else {
      user = await Calendly.create({ name, email, ...otherEventDetails });
    }

    res.json(user);
  } catch (err) {
    console.error('Error processing Calendly webhook:', err);
    res.sendStatus(500);
  }
};

export const fetchCalendlyEvent = async (req, res) => {
  try {
    const token = process.env.CALENDLY_ACCESS_TOKEN;
    const headers = { Authorization: `Bearer ${token}` };

    const response = await axios.get('https://api.calendly.com/scheduled_events', {
      params: { user: 'https://api.calendly.com/users/user-uri' },
      headers,
    });

    const eventDataCollection = response.data.collection;
    let allInvitees = [];

    for (const event of eventDataCollection) {
      const inviteesUri = `${event.uri}/invitees`;
      const inviteesResponse = await axios.get(inviteesUri, { headers });
      allInvitees = allInvitees.concat(inviteesResponse.data.collection);
    }

    await Calendly.deleteMany({});
    await Calendly.insertMany(allInvitees);

    res.status(201).json({ message: 'Events and invitees saved successfully' });
  } catch (error) {
    console.error('Error fetching Calendly events and invitees:', error);
    res.status(500).json({ error: error.message });
  }
};

export const getCalendlyEventById = async (req, res) => {
  try {
    const calendlyId = req.params.calendlyId;
    const calendly = await Calendly.findById(calendlyId);

    if (!calendly) {
      return res.status(404).json({ message: 'Calendly not found' });
    }

    res.status(200).json(calendly);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
};

export const refreshCalendlyEndpoint = async (req, res, next) => {
  try {
    await axios.post('https://localhost:8080/api/booking/calendly');
    next();
  } catch (error) {
    console.error('Error refreshing Calendly endpoint:', error);
    res.status(500).send('Error refreshing Calendly endpoint');
  }
};

export const getCalendly = async (req, res, next) => {
  try {
    const calendly = await Calendly.find();
    res.status(200).json(calendly);
  } catch (err) {
    next(err);
  }
};
Enter fullscreen mode Exit fullscreen mode
  1. Defining the Routes:
// routes/calendlyRoutes.js
import express from 'express';
import {
  createCalendly,
  fetchCalendlyEvent,
  getCalendlyEventById,
  refreshCalendlyEndpoint,
  getCalendly,
} from '../controllers/calendlyController.js';

const router = express.Router();

router.post('/create', createCalendly);
router.get('/fetch', fetchCalendlyEvent);
router.get('/:calendlyId', getCalendlyEventById);
router.post('/refresh', refreshCalendlyEndpoint);
router.get('/', getCalendly);

export default router;
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this comprehensive guide, we have demonstrated how to fetch event data from the Calendly API and save it into a MongoDB database using an Express.js application. We covered obtaining the access token from Calendly, setting up the project, creating a Mongoose model, defining route handlers for CRUD operations, and fetching data from the Calendly API. By following these steps, you can build a robust backend to manage Calendly events and invitees.

Top comments (0)