Back

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

Aug 12, 20246 minute read

Introduction

Hey there, fellow code wrangler! Ready to dive into the world of OnceHub API integration? You're in for a treat. OnceHub's API is a powerful tool that'll let you seamlessly incorporate scheduling functionality into your Ruby applications. Whether you're building a booking system or just want to automate your calendar, this guide will get you up and running in no time.

Prerequisites

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

  • Ruby 2.7+ installed (come on, you know you want those sweet new features)
  • Bundler for managing gems
  • Your OnceHub API credentials (if you don't have these yet, hop over to the OnceHub developer portal and grab 'em)

Setting Up the Project

Let's kick things off by setting up our project:

mkdir oncehub_integration cd oncehub_integration bundle init

Now, crack open that Gemfile and add these gems:

gem 'httparty' gem 'dotenv'

Run bundle install, and you're good to go!

Authentication

OnceHub uses API keys for authentication. Create a .env file in your project root and add your API key:

ONCEHUB_API_KEY=your_api_key_here

Now, let's set up a basic client:

require 'httparty' require 'dotenv/load' class OnceHubClient include HTTParty base_uri 'https://api.oncehub.com/v2' headers 'Authorization' => "Bearer #{ENV['ONCEHUB_API_KEY']}" end

Making API Requests

With our client set up, making requests is a breeze:

response = OnceHubClient.get('/bookings') puts response.body

Easy peasy, right? But don't forget to handle those pesky errors:

if response.success? puts response.body else puts "Error: #{response.code} - #{response.message}" end

Core Functionality Implementation

Let's implement some core features:

Fetching Available Time Slots

def fetch_available_slots(resource_id, date) response = OnceHubClient.get("/resources/#{resource_id}/availability", query: { date: date }) response.parsed_response if response.success? end

Creating Bookings

def create_booking(resource_id, start_time, end_time, customer_details) body = { resource_id: resource_id, start_time: start_time, end_time: end_time, customer: customer_details } response = OnceHubClient.post('/bookings', body: body.to_json) response.parsed_response if response.success? end

Error Handling and Logging

Let's add some robust error handling and logging:

require 'logger' class OnceHubClient # ... previous code ... @@logger = Logger.new(STDOUT) def self.handle_request response = yield if response.success? @@logger.info "Successful request: #{response.request.path}" response.parsed_response else @@logger.error "Error: #{response.code} - #{response.message}" raise "API Error: #{response.message}" end end def self.get(path, options = {}) handle_request { super } end def self.post(path, options = {}) handle_request { super } end end

Testing the Integration

Don't forget to test your integration! Here's a quick example using RSpec:

require 'rspec' require_relative 'oncehub_client' RSpec.describe OnceHubClient do it 'fetches available slots successfully' do slots = OnceHubClient.fetch_available_slots('resource_id', Date.today) expect(slots).not_to be_empty end it 'creates a booking successfully' do booking = OnceHubClient.create_booking('resource_id', Time.now, Time.now + 3600, { name: 'John Doe', email: '[email protected]' }) expect(booking).to have_key('id') end end

Best Practices and Optimization

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

require 'redis' class OnceHubClient # ... previous code ... @@redis = Redis.new def self.fetch_available_slots(resource_id, date) cache_key = "available_slots:#{resource_id}:#{date}" cached = @@redis.get(cache_key) return JSON.parse(cached) if cached slots = handle_request { get("/resources/#{resource_id}/availability", query: { date: date }) } @@redis.setex(cache_key, 300, slots.to_json) # Cache for 5 minutes slots end end

Conclusion

And there you have it! You've just built a solid OnceHub API integration in Ruby. You've got authentication, core functionality, error handling, testing, and even some optimization tips under your belt.

Remember, this is just the beginning. The OnceHub API has a lot more to offer, so don't be afraid to explore and expand on this foundation. Happy coding, and may your schedules always be in sync!