Back

Reading and Writing Data Using the Cal.com API

Aug 16, 20246 minute read

Hey there, fellow JavaScript enthusiasts! Ready to dive into the world of Cal.com API integration? Let's roll up our sleeves and get our hands dirty with some code. We'll focus on syncing data for a user-facing integration, so buckle up!

Authentication: Your Golden Ticket

First things first, you'll need to grab those API keys. Head over to your Cal.com dashboard and snag your credentials. Once you've got them, let's set up authentication in your app:

const calApi = require('@calcom/api'); const cal = new calApi.CalendarClient({ apiKey: 'your_api_key_here' });

Reading Data: What's on the Calendar?

Now that we're in, let's fetch some events and available time slots:

async function getEvents() { const events = await cal.events.list(); console.log(events); } async function getAvailability(date) { const slots = await cal.availability.list({ date }); console.log(slots); }

Easy peasy, right? You've just tapped into the calendar data!

Writing Data: Pencil It In

Time to add some events to the calendar:

async function createEvent(eventData) { const newEvent = await cal.events.create(eventData); console.log('New event created:', newEvent); } async function updateEvent(eventId, updateData) { const updatedEvent = await cal.events.update(eventId, updateData); console.log('Event updated:', updatedEvent); }

Boom! You're now a calendar wizard.

Syncing Data: Keep Everything in Harmony

Let's set up a basic sync function to keep your app and Cal.com in sync:

async function syncEvents() { const localEvents = getLocalEvents(); // Your local event fetching logic const calEvents = await cal.events.list(); for (const event of calEvents) { if (!localEvents.find(e => e.id === event.id)) { // Event doesn't exist locally, add it addEventToLocalStorage(event); } else { // Event exists, update it updateLocalEvent(event); } } // Handle deleted events for (const localEvent of localEvents) { if (!calEvents.find(e => e.id === localEvent.id)) { removeEventFromLocalStorage(localEvent.id); } } }

This function will keep your local storage and Cal.com events in perfect harmony. Sweet!

Webhooks: Real-time Magic

Want to stay on top of changes as they happen? Webhooks are your new best friend:

app.post('/webhook', (req, res) => { const event = req.body; switch (event.type) { case 'event.created': handleNewEvent(event.data); break; case 'event.updated': handleUpdatedEvent(event.data); break; case 'event.deleted': handleDeletedEvent(event.data); break; } res.sendStatus(200); });

Now you're cooking with gas! Your app will react to changes in real-time.

Error Handling and Rate Limiting: Play Nice

Remember to handle errors gracefully and respect those rate limits:

async function safeApiCall(apiFunction) { try { return await apiFunction(); } catch (error) { if (error.status === 429) { // Rate limited, wait and retry await new Promise(resolve => setTimeout(resolve, 5000)); return safeApiCall(apiFunction); } console.error('API Error:', error); throw error; } }

Best Practices: The Cherry on Top

  1. Cache data when possible to reduce API calls.
  2. Keep those API keys secret! Use environment variables.
  3. Sync smartly - don't hammer the API unnecessarily.

And there you have it! You're now equipped to build an awesome Cal.com integration. Remember, the API is your playground - experiment, create, and most importantly, have fun with it!

Happy coding, and may your calendars always be in sync! 🚀📅