Back

Reading and Writing Data Using the FareHarbor API

Aug 16, 20246 minute read

Hey there, fellow JavaScript aficionados! Ready to dive into the world of FareHarbor API integration? Let's get our hands dirty with some code and learn how to sync data for a user-facing integration. Buckle up!

Introduction

FareHarbor's API is your ticket to seamlessly integrating tour and activity bookings into your application. We're talking real-time availability, pricing, and booking management – all at your fingertips. Let's explore how to make this magic happen.

Authentication

First things first – you'll need to get cozy with FareHarbor's authentication process. Grab your API credentials from the FareHarbor dashboard, and let's implement OAuth 2.0 flow:

const axios = require('axios'); async function getAccessToken(clientId, clientSecret, code) { const response = await axios.post('https://fareharbor.com/api/external/v1/oauth/token/', { client_id: clientId, client_secret: clientSecret, code: code, grant_type: 'authorization_code' }); return response.data.access_token; }

Reading Data

Now that we're authenticated, let's fetch some data. Here's how to grab available items and their availability:

async function getAvailableItems(accessToken) { const response = await axios.get('https://fareharbor.com/api/external/v1/items/', { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.data.items; } async function getAvailability(accessToken, itemId, date) { const response = await axios.get(`https://fareharbor.com/api/external/v1/items/${itemId}/availability/date/${date}/`, { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.data.availabilities; }

Pro tip: Keep an eye on those rate limits and implement pagination for large datasets!

Writing Data

Time to make some bookings! Here's a quick example of creating a reservation:

async function createBooking(accessToken, availabilityId, customerData) { const response = await axios.post(`https://fareharbor.com/api/external/v1/availabilities/${availabilityId}/bookings/`, { customer: customerData, voucher_number: 'SUMMER2023' }, { headers: { 'Authorization': `Bearer ${accessToken}` } }); return response.data.booking; }

Syncing Strategies

Real-time updates are the name of the game. Implement webhooks to stay in sync:

const express = require('express'); const app = express(); app.post('/webhook', express.json(), (req, res) => { const event = req.body; // Handle the event based on its type switch (event.type) { case 'booking.created': // Update your local database break; case 'booking.cancelled': // Remove the booking from your system break; // ... handle other event types } res.sendStatus(200); });

Optimizing Performance

Cache, cache, cache! But don't forget to invalidate when necessary:

const NodeCache = require('node-cache'); const cache = new NodeCache({ stdTTL: 600 }); // 10 minutes async function getCachedAvailability(accessToken, itemId, date) { const cacheKey = `availability:${itemId}:${date}`; let availability = cache.get(cacheKey); if (!availability) { availability = await getAvailability(accessToken, itemId, date); cache.set(cacheKey, availability); } return availability; }

Error Handling and Logging

Always expect the unexpected. Wrap your API calls in try-catch blocks and log those errors:

const winston = require('winston'); const logger = winston.createLogger(/* your config here */); async function safeApiCall(apiFunction, ...args) { try { return await apiFunction(...args); } catch (error) { logger.error('API call failed', { function: apiFunction.name, error: error.message }); throw error; } }

Security Considerations

Keep those API keys safe! Use environment variables and never, ever commit them to version control:

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

Testing and Validation

Test, test, and test again! Use FareHarbor's sandbox environment to validate your integration:

const { expect } = require('chai'); describe('FareHarbor API', () => { it('should fetch available items', async () => { const items = await getAvailableItems(SANDBOX_ACCESS_TOKEN); expect(items).to.be.an('array'); expect(items.length).to.be.greaterThan(0); }); // More tests... });

Conclusion

And there you have it, folks! You're now armed with the knowledge to build a robust FareHarbor API integration. Remember to keep your code clean, your errors handled, and your data fresh. Happy coding, and may your bookings always be plentiful!

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