Back

Step by Step Guide to Building a OnceHub API Integration in JS

Aug 12, 20247 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of OnceHub API integration? You're in for a treat. OnceHub's API is a powerful tool that lets you seamlessly incorporate scheduling functionality into your applications. In this guide, we'll walk through the process of building a robust integration that'll have you scheduling like a pro in no time.

Prerequisites

Before we jump in, make sure you've got these bases covered:

  • A OnceHub account (if you don't have one, go grab it!)
  • Your shiny API key (you'll find this in your account settings)
  • Your favorite JS development environment set up and ready to roll

Got all that? Great! Let's get our hands dirty.

Setting up the project

First things first, let's get our project off the ground:

mkdir oncehub-integration cd oncehub-integration npm init -y npm install axios dotenv

We're using axios for HTTP requests and dotenv to manage our environment variables. Trust me, your future self will thank you for this setup.

Authentication

Now, let's tackle authentication. Create a .env file in your project root:

ONCEHUB_API_KEY=your_api_key_here

Then, in your main JS file:

require('dotenv').config(); const axios = require('axios'); const onceHubApi = axios.create({ baseURL: 'https://api.oncehub.com/v2', headers: { 'Authorization': `Bearer ${process.env.ONCEHUB_API_KEY}`, 'Content-Type': 'application/json' } });

Boom! You're authenticated and ready to make requests.

Making API requests

Let's start with a simple request to get your booking pages:

async function getBookingPages() { try { const response = await onceHubApi.get('/booking_pages'); console.log(response.data); } catch (error) { console.error('Error fetching booking pages:', error.response.data); } } getBookingPages();

Run this, and you should see your booking pages listed. Cool, right?

Core functionality implementation

Now for the fun part. Let's implement some core functionality:

Fetching available time slots

async function getAvailableSlots(bookingPageId, date) { try { const response = await onceHubApi.get(`/booking_pages/${bookingPageId}/availability?date=${date}`); return response.data.slots; } catch (error) { console.error('Error fetching available slots:', error.response.data); } }

Creating a booking

async function createBooking(bookingPageId, slotData, customerData) { try { const response = await onceHubApi.post(`/booking_pages/${bookingPageId}/bookings`, { slot: slotData, customer: customerData }); return response.data; } catch (error) { console.error('Error creating booking:', error.response.data); } }

Error handling and edge cases

Always expect the unexpected! Here's a more robust error handling approach:

function handleApiError(error) { if (error.response) { console.error(`API Error: ${error.response.status} - ${error.response.data.message}`); } else if (error.request) { console.error('No response received from the server'); } else { console.error('Error setting up the request:', error.message); } }

Use this in your try-catch blocks for better error management.

Testing the integration

Testing is crucial. Here's a quick example using Jest:

const { getBookingPages } = require('./your-main-file'); test('getBookingPages returns data', async () => { const result = await getBookingPages(); expect(result).toBeDefined(); expect(Array.isArray(result)).toBe(true); });

Optimization and best practices

Remember to respect rate limits and implement caching where appropriate. For instance:

const NodeCache = require('node-cache'); const cache = new NodeCache({ stdTTL: 600 }); // Cache for 10 minutes async function getCachedBookingPages() { const cacheKey = 'booking_pages'; let bookingPages = cache.get(cacheKey); if (!bookingPages) { bookingPages = await getBookingPages(); cache.set(cacheKey, bookingPages); } return bookingPages; }

Conclusion

And there you have it! You've just built a solid OnceHub API integration. You've got authentication, core functionality, error handling, and even some optimization tricks up your sleeve.

Remember, this is just the beginning. The OnceHub API has a lot more to offer, so don't be afraid to explore and experiment. Check out their official documentation for more advanced features and best practices.

Now go forth and schedule like a boss! Happy coding!