Hey there, fellow Ruby enthusiast! Ready to supercharge your app with Leadpages? Let's dive into building a slick API integration that'll have you pulling lead data like a pro. We'll keep things snappy and to the point, so buckle up!
Before we jump in, make sure you've got:
faraday
in this guide)First things first, let's get our project off the ground:
mkdir leadpages_integration cd leadpages_integration bundle init
Now, crack open that Gemfile
and add:
gem 'faraday' gem 'json'
Run bundle install
and we're cooking with gas!
Leadpages uses OAuth 2.0, so let's grab that access token:
require 'faraday' require 'json' client_id = 'your_client_id' client_secret = 'your_client_secret' conn = Faraday.new(url: 'https://api.leadpages.io/oauth/token') response = conn.post do |req| req.body = { grant_type: 'client_credentials', client_id: client_id, client_secret: client_secret } end token = JSON.parse(response.body)['access_token']
Pro tip: Store that token securely and handle refreshes like a champ!
Now that we're authenticated, let's make some noise:
api = Faraday.new(url: 'https://api.leadpages.io/') do |f| f.headers['Authorization'] = "Bearer #{token}" f.headers['Content-Type'] = 'application/json' end # GET request response = api.get('v3/leads') # POST request response = api.post('v3/leads') do |req| req.body = { email: '[email protected]' }.to_json end
Let's put that API to work:
# Fetch leads leads = JSON.parse(api.get('v3/leads').body) # Create a new lead new_lead = JSON.parse(api.post('v3/leads') do |req| req.body = { email: '[email protected]' }.to_json end.body) # Update a lead updated_lead = JSON.parse(api.put("v3/leads/#{lead_id}") do |req| req.body = { first_name: 'John' }.to_json end.body) # Get landing page data landing_page = JSON.parse(api.get("v3/landing_pages/#{page_id}").body)
Don't let those pesky errors catch you off guard:
begin response = api.get('v3/leads') raise unless response.success? # Handle successful response rescue Faraday::Error => e puts "API request failed: #{e.message}" # Log error, retry, or handle gracefully end
Test early, test often:
require 'minitest/autorun' require 'webmock/minitest' class LeadpagesIntegrationTest < Minitest::Test def setup @api = LeadpagesAPI.new(token: 'fake_token') end def test_fetch_leads stub_request(:get, "https://api.leadpages.io/v3/leads") .to_return(status: 200, body: '{"leads": []}') assert_equal [], @api.fetch_leads end end
And there you have it! You're now armed and dangerous with a Leadpages API integration in Ruby. Remember, the API is your oyster – explore, experiment, and build something awesome. Happy coding, and may your leads be ever-flowing!