Back

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

Aug 12, 20246 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 programmatically manage bookings, and we're going to build an integration using Python. Buckle up!

Prerequisites

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

  • A Python environment (3.6+ recommended)
  • The requests library installed (pip install requests)
  • Your OnceHub API credentials (if you don't have these, hop over to your OnceHub account and grab them)

Authentication

First things first, let's get you authenticated:

import requests API_KEY = 'your_api_key_here' HEADERS = { 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json' }

Pro tip: Never hardcode your API key in production. Use environment variables or a secure config file.

Basic API Request Structure

OnceHub's API is RESTful, so we'll be working with standard HTTP methods. Here's a quick example:

BASE_URL = 'https://api.oncehub.com/v2' def make_request(endpoint, method='GET', data=None): url = f'{BASE_URL}/{endpoint}' response = requests.request(method, url, headers=HEADERS, json=data) response.raise_for_status() return response.json()

Core Functionality Implementation

Fetching Bookings

Let's grab those bookings:

def get_bookings(): return make_request('bookings') bookings = get_bookings() print(f"You have {len(bookings)} bookings.")

Creating a Booking

Time to add a new booking:

def create_booking(booking_data): return make_request('bookings', method='POST', data=booking_data) new_booking = create_booking({ 'resource_id': 'your_resource_id', 'start_time': '2023-06-01T09:00:00Z', 'end_time': '2023-06-01T10:00:00Z', 'customer': {'name': 'John Doe', 'email': '[email protected]'} }) print(f"New booking created with ID: {new_booking['id']}")

Updating a Booking

Need to make changes? No problem:

def update_booking(booking_id, update_data): return make_request(f'bookings/{booking_id}', method='PUT', data=update_data) updated_booking = update_booking('booking_id_here', {'start_time': '2023-06-01T10:00:00Z'}) print(f"Booking updated: {updated_booking}")

Canceling a Booking

Sometimes things don't go as planned:

def cancel_booking(booking_id): return make_request(f'bookings/{booking_id}', method='DELETE') cancel_booking('booking_id_here') print("Booking canceled successfully.")

Error Handling and Response Parsing

Let's add some error handling to our make_request function:

from requests.exceptions import RequestException def make_request(endpoint, method='GET', data=None): url = f'{BASE_URL}/{endpoint}' try: response = requests.request(method, url, headers=HEADERS, json=data) response.raise_for_status() return response.json() except RequestException as e: print(f"An error occurred: {e}") return None

Advanced Features

Pagination

OnceHub uses cursor-based pagination. Here's how to handle it:

def get_all_bookings(): bookings = [] next_cursor = None while True: params = {'cursor': next_cursor} if next_cursor else {} response = make_request('bookings', params=params) bookings.extend(response['data']) next_cursor = response.get('next_cursor') if not next_cursor: break return bookings

Best Practices

  • Respect rate limits: OnceHub has rate limits, so consider implementing exponential backoff for retries.
  • Use webhook notifications when possible instead of polling the API frequently.
  • Keep your API key secure and rotate it regularly.

Testing the Integration

Here's a simple unit test to get you started:

import unittest from unittest.mock import patch class TestOnceHubIntegration(unittest.TestCase): @patch('requests.request') def test_get_bookings(self, mock_request): mock_request.return_value.json.return_value = {'data': [{'id': '1'}]} bookings = get_bookings() self.assertEqual(len(bookings['data']), 1) if __name__ == '__main__': unittest.main()

Conclusion

And there you have it! You've just built a solid OnceHub API integration in Python. Remember, this is just the beginning - there's so much more you can do with the OnceHub API. Keep exploring, keep coding, and most importantly, have fun!

For more details, check out the OnceHub API documentation. Happy coding!