Hey there, fellow developer! Ready to dive into the world of Facebook Custom Audiences? Let's roll up our sleeves and build an API integration using Ruby. This guide assumes you're already familiar with Ruby and have some context about Facebook's marketing tools. We'll keep things concise and to the point, so you can get up and running in no time.
Before we jump in, make sure you've got:
Got all that? Great! Let's move on.
First things first, let's get the facebookbusiness
gem installed:
gem install facebookbusiness
Easy peasy, right?
Now, let's initialize the API client and set up our access token:
require 'facebook_ads' FacebookAds.configure do |config| config.access_token = 'YOUR_ACCESS_TOKEN' config.app_secret = 'YOUR_APP_SECRET' end ad_account = FacebookAds::AdAccount.get('act_<AD_ACCOUNT_ID>')
Replace those placeholders with your actual credentials, and you're good to go!
Time to create our first Custom Audience:
audience = ad_account.custom_audiences.create({ name: 'My Ruby Custom Audience', description: 'Audience created via Ruby API', subtype: 'CUSTOM' }) puts "Created audience with id: #{audience.id}"
Boom! You've just created your first Custom Audience programmatically.
Now, let's add some users to our shiny new audience:
users = [ {email: '[email protected]'}, {email: '[email protected]'} ] hashed_users = users.map do |user| {email_hash: Digest::SHA256.hexdigest(user[:email].downcase)} end audience.users.create({ payload: { schema: ['EMAIL_SHA256'], data: hashed_users } })
Pro tip: Always hash your user data before sending it to Facebook. It's not just best practice, it's required!
Curious about your audience? Let's fetch some details:
audience = FacebookAds::CustomAudience.get(audience.id) puts "Audience Name: #{audience.name}" puts "Audience Size: #{audience.approximate_count}"
Need to make some changes? No problem:
audience.update({ name: 'Updated Ruby Custom Audience', description: 'This audience has been updated' })
All good things must come to an end. Here's how to delete an audience:
audience.destroy puts "Audience deleted successfully"
And there you have it! You've just built a Facebook Custom Audiences API integration in Ruby. From creating and populating audiences to updating and deleting them, you're now equipped to programmatically manage your Custom Audiences like a pro.
Remember, this is just the tip of the iceberg. There's so much more you can do with the Facebook Marketing API. So go forth and experiment!
Happy coding, and may your audiences be ever targeted!