Hey there, fellow Ruby enthusiast! Ready to supercharge your marketing automation? Let's dive into building a Klaviyo API integration. Klaviyo's powerful API allows you to sync customer data, track events, and manage email campaigns programmatically. Buckle up, because we're about to make your Ruby app a lot smarter!
Before we jump in, make sure you've got:
httparty
gem (we'll use this for API requests)Let's get our hands dirty:
mkdir klaviyo_integration cd klaviyo_integration bundle init
Open your Gemfile and add:
gem 'httparty'
Then run:
bundle install
Create a new file called klaviyo_client.rb
:
require 'httparty' class KlaviyoClient include HTTParty base_uri 'https://a.klaviyo.com/api' def initialize(api_key) @api_key = api_key end # We'll add more methods here soon! end
Let's add some methods to our KlaviyoClient
class:
def get_lists self.class.get("/v2/lists", query: { api_key: @api_key }) end def create_list(list_name) self.class.post("/v2/lists", body: { list_name: list_name }, query: { api_key: @api_key } ) end def add_subscriber(list_id, email) self.class.post("/v2/list/#{list_id}/members", body: { email: email }, query: { api_key: @api_key } ) end
Time to track some events:
def track_event(event_name, customer_properties, properties) self.class.post("/v2/track", body: { token: @api_key, event: event_name, customer_properties: customer_properties, properties: properties } ) end
Let's add profile management:
def create_profile(email, properties) self.class.post("/v2/people", body: { email: email, properties: properties }, query: { api_key: @api_key } ) end def update_profile(email, properties) self.class.put("/v2/people", body: { email: email, properties: properties }, query: { api_key: @api_key } ) end
Always handle your errors gracefully:
def api_request response = yield if response.success? JSON.parse(response.body) else raise "API Error: #{response.code} - #{response.message}" end end
Wrap your API calls with this method to catch and handle errors consistently.
Here's a quick test script to make sure everything's working:
require_relative 'klaviyo_client' client = KlaviyoClient.new('your-api-key') # Test getting lists puts client.get_lists # Test creating a list new_list = client.create_list('My Awesome List') puts new_list # Test adding a subscriber client.add_subscriber(new_list['list_id'], '[email protected]') # Test tracking an event client.track_event('Viewed Product', { '$email': '[email protected]' }, { 'Product Name': 'Awesome Widget' } )
And there you have it! You've just built a solid foundation for integrating Klaviyo into your Ruby app. Remember, this is just scratching the surface - Klaviyo's API has tons more features to explore.
Keep experimenting, and don't forget to check out Klaviyo's official API docs for more advanced use cases. Happy coding, and may your email campaigns be ever successful!