Back

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

Aug 16, 2024 • 6 minute read

Introduction

Hey there, fellow code wrangler! Ready to dive into the world of FareHarbor API integration? Buckle up, because we're about to embark on a journey that'll have you booking experiences like a pro in no time. FareHarbor's API is your ticket to accessing a treasure trove of tour and activity data, and we're going to make it sing with JavaScript.

Prerequisites

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

  • A FareHarbor API key (if you don't have one, go grab it from your FareHarbor dashboard)
  • Your favorite code editor
  • A burning desire to make awesome things happen

Setting Up the Development Environment

Let's get this party started:

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

Boom! You're ready to roll.

Authentication

First things first, let's keep that API key safe:

require('dotenv').config(); const apiKey = process.env.FAREHARBOR_API_KEY;

Making API Requests

Time to make some noise:

const axios = require('axios'); const baseURL = 'https://fareharbor.com/api/external/v1/'; const api = axios.create({ baseURL, headers: { 'X-FareHarbor-API-App': apiKey } });

Core API Functionalities

Let's get those items and check availability:

async function getAvailableItems(companyShortName) { try { const response = await api.get(`companies/${companyShortName}/items/`); return response.data.items; } catch (error) { console.error('Error fetching items:', error); } } async function checkAvailability(companyShortName, itemId, date) { try { const response = await api.get(`companies/${companyShortName}/items/${itemId}/availability/date/${date}/`); return response.data.availabilities; } catch (error) { console.error('Error checking availability:', error); } }

Data Parsing and Manipulation

Now, let's make that data shine:

function formatAvailability(availabilities) { return availabilities.map(a => ({ start: new Date(a.start_at), end: new Date(a.end_at), capacity: a.capacity, spotsLeft: a.capacity - a.customer_count })); }

Implementing Webhook Support

FareHarbor's got your back with real-time updates:

const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const { type, payload } = req.body; // Handle different webhook types here console.log(`Received webhook of type: ${type}`); res.sendStatus(200); }); app.listen(3000, () => console.log('Webhook server running on port 3000'));

Error Handling and Edge Cases

Let's catch those curveballs:

async function makeApiCall(fn) { try { return await fn(); } catch (error) { if (error.response && error.response.status === 429) { // Handle rate limiting await new Promise(resolve => setTimeout(resolve, 1000)); return makeApiCall(fn); } throw error; } }

Testing and Debugging

Keep it clean, folks:

const assert = require('assert'); describe('FareHarbor API', () => { it('should fetch available items', async () => { const items = await getAvailableItems('your-company-shortname'); assert(Array.isArray(items)); }); });

Performance Optimization

Cache it like it's hot:

const NodeCache = require('node-cache'); const cache = new NodeCache({ stdTTL: 600 }); async function getCachedItems(companyShortName) { const cacheKey = `items_${companyShortName}`; let items = cache.get(cacheKey); if (!items) { items = await getAvailableItems(companyShortName); cache.set(cacheKey, items); } return items; }

Security Considerations

Keep those secrets secret:

// .env FAREHARBOR_API_KEY=your_api_key_here // Never commit this file to version control!

Deployment Considerations

Ready for the big leagues:

const apiVersion = 'v1'; const apiUrl = process.env.NODE_ENV === 'production' ? `https://fareharbor.com/api/external/${apiVersion}/` : `https://demo.fareharbor.com/api/external/${apiVersion}/`;

Conclusion

And there you have it, folks! You've just built a rock-solid FareHarbor API integration. Remember, this is just the beginning. The API has tons more to offer, so keep exploring and building awesome things.

For more in-depth info, check out the FareHarbor API docs. Now go forth and book all the things!

Happy coding, you magnificent developer, you! 🚀