Back

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

Aug 16, 20246 minute read

Introduction

Hey there, fellow developer! Ready to dive into the world of FareHarbor API integration? You're in for a treat. This guide will walk you through the process of building a robust integration using Python. FareHarbor's API is a powerful tool for managing bookings and availability for tour and activity businesses. Let's get our hands dirty and build something awesome!

Prerequisites

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

  • A Python environment (3.6+ recommended)
  • requests library installed (pip install requests)
  • Your FareHarbor API credentials (we'll talk more about this in a sec)

Authentication

First things first, let's get you authenticated:

  1. Grab your API key and App key from your FareHarbor dashboard.
  2. Set up your headers like this:
headers = { 'X-FareHarbor-API-App': 'YOUR_APP_KEY', 'X-FareHarbor-API-User': 'YOUR_USER_KEY' }

Basic API Request Structure

Now, let's talk about making requests. Here's the basic structure:

import requests base_url = 'https://fareharbor.com/api/external/v1/' endpoint = 'companies/COMPANY_SHORTNAME/items/' response = requests.get(base_url + endpoint, headers=headers)

Core API Functionalities

Let's cover the essentials:

Retrieving Available Items

def get_items(): endpoint = f'companies/{COMPANY_SHORTNAME}/items/' response = requests.get(base_url + endpoint, headers=headers) return response.json()

Checking Availability

def check_availability(item_id, date): endpoint = f'companies/{COMPANY_SHORTNAME}/items/{item_id}/availability/date/{date}/' response = requests.get(base_url + endpoint, headers=headers) return response.json()

Creating Bookings

def create_booking(availability_id, customer_data): endpoint = f'companies/{COMPANY_SHORTNAME}/availabilities/{availability_id}/bookings/' payload = { "contact": customer_data, "customers": [{"customer_type_rate": "adult"}] } response = requests.post(base_url + endpoint, json=payload, headers=headers) return response.json()

Error Handling and Rate Limiting

Always handle your errors gracefully:

def api_request(endpoint, method='GET', data=None): try: if method == 'GET': response = requests.get(base_url + endpoint, headers=headers) elif method == 'POST': response = requests.post(base_url + endpoint, json=data, headers=headers) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"API request failed: {e}") return None

For rate limiting, keep an eye on the X-RateLimit-Remaining header.

Data Processing and Storage

Parse that JSON like a boss:

import json def process_items(items_data): for item in items_data['items']: # Process each item as needed print(f"Item: {item['name']}, ID: {item['pk']}")

Advanced Features

Webhook Integration

Set up a simple Flask server to handle webhooks:

from flask import Flask, request app = Flask(__name__) @app.route('/webhook', methods=['POST']) def handle_webhook(): data = request.json # Process webhook data return '', 200 if __name__ == '__main__': app.run(port=5000)

Testing and Debugging

Always test your API calls:

import unittest class TestFareHarborAPI(unittest.TestCase): def test_get_items(self): items = get_items() self.assertIsNotNone(items) self.assertIn('items', items) if __name__ == '__main__': unittest.main()

Best Practices and Optimization

  • Cache frequently accessed data to reduce API calls.
  • Use asynchronous requests for better performance when making multiple calls.
import asyncio import aiohttp async def fetch_item(session, item_id): endpoint = f'companies/{COMPANY_SHORTNAME}/items/{item_id}/' async with session.get(base_url + endpoint) as response: return await response.json() async def fetch_all_items(item_ids): async with aiohttp.ClientSession(headers=headers) as session: tasks = [fetch_item(session, item_id) for item_id in item_ids] return await asyncio.gather(*tasks)

Conclusion

And there you have it! You've just built a solid FareHarbor API integration in Python. Remember, this is just the beginning. Keep exploring the API documentation, experiment with different endpoints, and don't be afraid to push the boundaries of what you can do.

Happy coding, and may your bookings always be plentiful!