Git Product home page Git Product logo

facebook-ruby-business-sdk's Introduction

Facebook Business SDK for Ruby

Packagist License Build Status


The Facebook Business SDK is a one-stop shop to help our partners better serve their businesses. Partners are using multiple Facebook API's to serve the needs of their clients. Adopting all these API's and keeping them up to date across the various platforms can be time consuming and ultimately prohibitive. For this reason Facebook has developed the Business SDK bundling many of its APIs into one SDK to ease implementation and upkeep. The Business SDK is an upgraded version of the Marketing API SDK that includes the Marketing API as well as many Facebook APIs from different platforms such as Pages, Business Manager, Instagram, etc.

Quick Start

Business SDK Getting Started Guide


Ruby Version

The minimum version supported is Ruby 3.0.

Register An App

To get started with the SDK, you must have an app registered on

To manage the Marketing API, please visit your App Dashboard and add the Marketing API product to your app.

IMPORTANT: For security, it is recommended that you turn on 'App Secret Proof for Server API calls' in your app's Settings->Advanced page.

Obtain An Access Token

When someone connects with an app using Facebook Login and approves the request for permissions, the app obtains an access token that provides temporary, secure access to Facebook APIs.

An access token is an opaque string that identifies a User, app, or Page.

For example, to access the Marketing API, you need to generate a User access token for your app and ask for the ads_management permission; to access Pages API, you need to generate a Page access token for your app and ask for the manage_page permission.

Refer to our Access Token Guide to learn more.

For now, we can use the Graph Explorer to get an access token.


The SDK is available as a RubyGem. To use the gem, you can add the following to Gemfile

gem 'facebookbusiness'

or install it using command line

gem install facebookbusiness

and then in your code

require 'facebookbusiness'


Access Token

There are several ways to configure access token and app secret. If you only use one access token and app secret (example: an internal app managing only your own assets). You can set a global access token and app secret will be used across all requests

FacebookAds.configure do |config|

Another way is to configure using environment variables, which will be picked up by the SDK as the default


Or you can create a session object for particular object

# Create a Session object to be reused
session = <ACCESS_TOKEN>, app_secret: <APP SECRET>)
ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name', session)

# Or a using shortcut during object instantiation
ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name', {
    access_token: <ACCESS_TOKEN>, app_secret: <APP SECRET>

Basic Operations

Reading a node

The SDK contains ad object files auto generated from our API metadata, each node type has its own corresponding Ruby class under the FacebookAds module. For example, to fetch an AdAccount

ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name')
puts "Ad Account Name: #{}"

The #get method doesn't trigger the GET request immediately. The API request for GET is fired on-demand. In the example above, API request won't fire until is executed.

Updating a node

To update a node, you can use the #save method of ad object classes.

ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name') = "New Ad Account"

# Fetch it again
=> "New Ad Account"

Deleting a node

To delete a node, you can use the #destroy method.

campaign = FacebookAds::Campaign.get('<CAMPAIGN_ID>')


You can refer to our Marketing API reference or look inside lib/facebook_ads/ad_objects directory of the code base to see the complete list of available ad objects.

Interacting with Edges

To interact with an edge, you first need to instantiate the parent node. Since, as mentioned above, GET request of a node is triggered on-demand, so you don't need to worry about consuming unnecessary API quota.

Fetching Edges (GET)

Iterating edges is easy, instantiate the parent nodes and then simply iterate with #each. The edge is an Enumerable so a bunch of handy methods such as #map, #select, #find etc. come for free!

ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name')

# Printing all campaign names
ad_account.campaigns(fields: 'name').each do |campaign|

# Getting all campaign names
ad_account.campaigns(fields: 'name').map(&:name)

Creating new nodes (POST)

To POST to a edge, you can use the #create method on the edge and supply parameter if needed

campaign = ad_account.campaigns.create({
  name: "My First campaign",
  objective: "CONVERSIONS",

Removing from edge (DELETE)

To DELETE an edge, you can use the #destroy method on the edge and supply parameter if needed

# Deleting an AdImage by its hash
ad_account.adimages.destroy({hash: 'abcd1234'})


The SDK supports image/video uploads. Just supply a parameter of File type.

Image upload example:

# AdImage supports multiple images upload
  'logo1.png' =>'./assets/logo1.jpg'),
  'logo2.png' =>'./assets/logo2.jpg'),
=> [#<FacebookAds::AdImage {:hash=>"..."}>, #<FacebookAds::AdImage {:hash=>"..."}>]

Video upload example:

  name: 'My first video',
  source:"../video_ad_example.mp4", __FILE__))

Batch API

Batch API allows you to make API calls in a batch. You can collect a bunch of API requests and fire them all at once to reduce wait time. To create a batch, just wrap operations with a block to FacebookAds::Batch#with_batch

ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>')

batch = FacebookAds::Batch.with_batch do do |n|
      name: 'My Test Campaign #' + n,
      objective: 'CONVERSIONS',
      status: 'PAUSED',


Dependencies within a batch (Experimental)

Dependencies between requests is supported, the SDK simplifies the use of JSONPath references between batched operations.

ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>')

batch = FacebookAds::Batch.with_batch do
  # This won't be sent out immediately!
  campaign = ad_account.campaigns.create({
    name: 'My Test Campaign',
    objective: 'CONVERSIONS',
    status: 'PAUSED',

  # Even the request above is not being sent yet, reference to still works
    name: 'My AdSet',
    campaign_id:, # here will return {result=create-campaign:$.id}


FacebookAds.configure do |config|
  # Logger for debugger
  config.logger = { |d| d.level = Logger::DEBUG }

  # Log Http request & response to logger
  config.log_api_bodies = true

SDK Codegen

Our SDK is autogenerated from SDK Codegen. If you want to learn more about how our SDK code is generated, please check this repository.

Reporting Bugs/Feedback

Please raise any issue on GitHub.


Facebook Business SDK for Ruby is licensed under the LICENSE file in the root directory of this source tree.

facebook-ruby-business-sdk's People


abetomo avatar alanho avatar andrelago13 avatar codytwinton avatar cp avatar dependabot[bot] avatar dipth avatar dlackty avatar ellentao avatar henrik avatar heymultiverse avatar icole avatar ivan-skotsyk avatar jingping2015 avatar joesus avatar kongxinzhu avatar linmouwu avatar maiha avatar marksliva avatar mktktmr avatar neilxchen avatar osdakira avatar rassas avatar stcheng avatar thomasmarshall avatar vicdus avatar walt1020 avatar windsfantasy6 avatar zertosh avatar


 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar


 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

facebook-ruby-business-sdk's Issues

Use native DateTime methods


Found one issue when using FacebookAds::FieldTypes::DateTime

module FacebookAds
  module FieldTypes
    class DateTime < Base
      def deserialize(value, session = nil)
           when String
            DateTime.strptime(value, '%FT%T%:z')

      def serialize(value)
          when String

when it calls either deserialize or serialize with string value, it's calling either DateTime.parse or DateTime.strptime but since current class name is same as DateTime, it will try to find a method in current class not from native one.


we can update them to ::DateTime.strptime and ::DateTime.parse

FacebookAds::Campaign.get('uid') return syntax error

Please fix that error
api.has_param :fb:channel, 'string'
api.has_param :image:height, 'int' ....

in files

uninitialized constant FAMEAdCampaign
must be a FameAdCampaign
in /lib/facebook_ads/ad_objects/campaign.rb


Get Amount spend from campaign

Hey, I cannot get from a campagin the amount spend.
I tryed many fields ( dayli_spend, spend, amount spend etc.. ) :
undefined method `amount_spent' for #FacebookAds::Campaign:0x007f8903ae49b0
Any ideas ?

Thanks :)

removing users from custom audience is throwing error ''Data is missing or does not match schema:"

removing users from custom audience is throwing error ''Data is missing or does not match schema:"

I am using

ca = FacebookAds::CustomAudience.get(<ad_account_id>, {
access_token: <Access_token>,
app_secret: <app_secret>
users = [['FirstName', '[email protected]', 'LastName1'],
['FirstNameTest', '[email protected]', 'LastNameTest']]

schema = ["FN","EMAIL","LN"]

ca.remove_user(users, schema)

When I execute above code I am getting error-- (#100) Data is missing or does not match schema:

Does not work with faraday < 0.9.2

get this error whenever trying to make a post request to upload image

ArgumentError: wrong number of arguments (given 3, expected 1..2)
from /Users/davidhu/.rvm/gems/ruby-2.3.0/gems/faraday-0.9.0/lib/faraday/response/logger.rb:7:in `initialize'

I am using faraday-0.9.0

in faraday 0.9.0

def initialize(app, logger = nil)

in faraday 0.9.2

def initialize(app, logger = nil, options = {})

This error is caused by Facebook SDK expecting the initialize method in logger.rb to accept 1..3 arguments instead of 1..2

How can i get Facebook error codes from a "FacebookAds::ClientError"

What's the issue?

When handling errors with Facebook, best practice is to use the error codes since the descriptions can change.

Facebook lays out the error codes here to make it easier to handle:

Observed Results:

It looks like the only things being returned are fb_message, error_user_title and fbtrace_id
according to this:

Expected Results:

It should return an error code for the message being returned


Is there any way to get this error code that belongs to the message?

Question about "facebook-ruby-ads-sdk custom audience" registration

Hi, I am trying to make a registration of a custom audience using "facebook-ruby-ads-sdk" (gem is below).
I am using the source below.

When I specify the schema "UID" and use the method "add_user",
"is_raw" parameter is set to "true" in the library, and request to the Marketing API got sent.

The UID is hashed based on Digest::SHA256.hexdigest(data) in the gem.
When data is hashed, which "is_raw" parameter is correct, "true" or "false" ?

I appreciate for your support.

Cant edit nested values in an Adset, ex. adset.targeting.age_min

Which SDK version are you using?


What's the issue?

When editing an AdSet that is fetched from Facebook, this works.

adset = FacebookAds::AdSet.get(id) = 'This is a test value'

But if you try updating something nests, such as the age_min, it does not set the value.

adset = FacebookAds::AdSet.get(id)
adset.targeting.age_min = 20

Expected Results:

It should set the value and update the AdSet

undefined method `destroy' for class `FacebookAds::AdsPixel' on 0.3.1 up to

This code:

    def sdk_ad_account
      @sdk_ad_account ||= FacebookAds::AdAccount.get(

Gives me this error:

       undefined method `destroy' for class `FacebookAds::AdsPixel'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `block in included'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `class_eval'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `included'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `include'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `has_no_delete'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `<class:AdsPixel>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `<module:FacebookAds>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `<top (required)>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `block in require'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:258:in `load_dependency'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `block (3 levels) in <class:AdAccount>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `initialize'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `new'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `for'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `has_param'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `block (2 levels) in <class:AdAccount>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `get'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `block in <class:AdAccount>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `has_edge'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `<class:AdAccount>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `<module:FacebookAds>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/facebookbusiness- `<top (required)>'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `block in require'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:258:in `load_dependency'
     # /Users/alex/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/dependencies.rb:292:in `require'
     # ./lib/facebook/client.rb:22:in `sdk_ad_account'

This makes this gem unusable, basically.

Filtering doesn't work on FacebookAds::Ad Leads

ad_id = XXXXXX

    filtering: [{ 
        value: '2018-12-12T12:00:00-0800'

In my example when I run the code above I get all the leads instead of the ones that are created after 12/12/2018.

No matter what I tried it always returns the all leads. Not sure if I'm doing something wrong or filtering not working.

The parameter filtering[0][operator] is required

When I use filtering to find out some campaigns with ids, it said that The parameter filtering[0][operator] is required, but I confirm I have the operator params,the code is below:

ad_account.campaigns(filtering: [{"field":"id","operator":"EQUAL", "value":"23842979460490127"}]).all

how can I use the filtering correctly? Thank you very much!

(#2654) The specified engagement rule is invalid

The error I got from console is:
FacebookAds::ClientError: (#2654) The specified engagement rule is invalid: Invalid subrule, subrule should be a json object: (fbtrace_id: C8drVEH1UbS)

Code is:

ca = ad_acc.customaudiences.create({
                                             name: "#{Rails.env}-PECA-#{}",
                                             subtype: 'ENGAGEMENT',
                                             description: "#{}'s page engagement custom audiences.",
                                             rule: {
                                                 object_id: tuition_center.facebook_ad_page_id,
                                                 event_name: "page_engaged"

Full Documentation

Is there anywhere I can get full documentation to the functionality of this gem?

FieldTypes issue related to Ad Account Delivery Estimate

When I request delivery_estimate from edges of ad_account, it raised TypeError. estimate_dau and estimate_mau in Ad Account Delivery Estimate defined as object like below, but both fields returned as integer from API.

Other types (like string_type or list) has several ways to handling if inputted different type of value what you expected are inputted. but object type is not, it's always trying parse JSON. bid_estimate defined as object, and it occurred TypeError too. because bid_estimate already has Hash at this point, not JSON string.

I tried like below...

ad_account = FacebookAds::AdAccount.get(<AD_ACCOUNT_ID>, <SESSION>)

# TypeError: no implicit conversion of Hash into String
# from /Users/san/.rvm/gems/ruby-2.3.4/gems/json-1.8.6/lib/json/common.rb:155:in `initialize'

read after write not working for adimages?

No matter what I put in fields I always get back image hash and url

I modified the example image_upload.rb file as follows:

images = ad_account.adimages.create({
  logo1:"../logo1.jpg", __FILE__)),
  logo2:"../logo2.png", __FILE__)),
  fields: ['name','hash']

and the object I get back contains hash and url attributes.

#<FacebookAds::AdImage {:hash=>"XXXXXXXXXX", :url=>""}>

Is read after write supported for ad images?

Not compatible with `frozen_string_literal: true`

The gem in its current form is not compatible with frozen string literals as destructive methods like gsub! are used.

Here is an example:

# frozen_string_literal: true
FacebookAds::AdAccount.get('act_12345', 'name)

#=> RuntimeError: can't modify frozen String
#=> from .../gems/facebookads- `gsub!'

Immutable string literals will be the default in ruby 3, so it might be a good idea to already stop using destructive string methods.

Edit: It gets better as of course things like the following won't work either, as the result is already immutable without any additional magic comment:

FacebookAds::AdAccount.get(ENV['FB_AD_ACCOUNT_ID'], 'name)

It's generally bad practice to mutate an input parameter like this.

AdCampaignDeliveryEstimate TypeError problems

Hi, maybe I'm not getting something here but when I get delivery estimate for adset I cannot read the responses data, almost all methods beside to_yaml return

TypeError: no implicit conversion of Hash into String. It seems to me like there is a bug in the gem.

Question: get edges within one api call


Is it possible to get the edge's data within a single api call ?

For example, I'd like to retrieve the ads within campaigns from my ad_account.
The graphql query i'd like : act_XXX?fields=campaigns{name,ads{name}}

I'm able to retrieve the campaigns ad_account.campaigns(fields: [:name]) but I can't manage to get the ads.

How can we do such a query?

Typo in Example

In create_custom_audience.rb add_users should be add_user.

No create method for AdSet

Which SDK version are you using?

Ruby 2.6.0
facebookbusiness gem from versions to

What's the issue?

In versions >, FacebookAds::AdAccount.get("XXX").adsets has lost the create method.
This example to create an AdSet does not work as a result:

Steps/Sample code to reproduce the issue

Observed Results:

Current traceback

$ gem uninstall facebookbusiness -s
$ gem install facebookbusiness -v
$ irb
2.6.0 :001 > require 'facebookbusiness'
 => true 
2.6.0 :002 > act = FacebookAds::AdAccount.get("act_XXXXXXXXXXXXXXXX")
 => #<FacebookAds::AdAccount {:id=>"act_XXXXXXXXXXXXXXXX"}> 
2.6.0 :003 > act.adsets.create({})
Traceback (most recent call last):
        4: from /home/mtamdev/.rvm/rubies/ruby-2.6.0/bin/irb:23:in `<main>'
        3: from /home/mtamdev/.rvm/rubies/ruby-2.6.0/bin/irb:23:in `load'
        2: from /home/mtamdev/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        1: from (irb):3
NoMethodError (undefined method `create' for #<#<Class:0x00007fffbc0d4e40>:0x00007fffbc3c51b8>)

Expected Results:

Intended traceback

$ gem uninstall facebookbusiness -s
$ gem install facebookbusiness -v
$ irb
2.6.0 :001 > require 'facebookbusiness'
 => true
2.6.0 :002 > act = FacebookAds::AdAccount.get("act_XXXXXXXXXXXXXXXX")
 => #<FacebookAds::AdAccount {:id=>"act_XXXXXXXXXXXXXXXX"}>
2.6.0 :003 > act.adsets.create({})
  Traceback (most recent call last):
    9: from /home/mtamdev/.rvm/rubies/ruby-2.6.0/bin/irb:23:in `<main>'
    8: from /home/mtamdev/.rvm/rubies/ruby-2.6.0/bin/irb:23:in `load'
    7: from /home/mtamdev/.rvm/rubies/ruby-2.6.0/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
    6: from (irb):3
    5: from /home/mtamdev/.rvm/gems/ruby-2.6.0@dataclover-core/gems/facebookbusiness- `create'
    4: from /home/mtamdev/.rvm/gems/ruby-2.6.0@dataclover-core/gems/facebookbusiness- `block (2 levels) in <class:AdObject>'
    3: from /home/mtamdev/.rvm/gems/ruby-2.6.0@dataclover-core/gems/facebookbusiness- `execute'
    2: from /home/mtamdev/.rvm/gems/ruby-2.6.0@dataclover-core/gems/facebookbusiness- `execute_now'
    1: from /home/mtamdev/.rvm/gems/ruby-2.6.0@dataclover-core/gems/facebookbusiness- `create_response'
FacebookAds::ClientError (Invalid parameter: Required Field Is Missing (fbtrace_id: A7woqYlpigEe5jPHM0rA_nw))

Invalid field type (map<string, unsigned int>)


There are two places using invalid field types (map<string, unsigned int>) in and

so it doesn't get found in when data for the field returned, and it returns as string

so when it returns hash object { 'foo' => 'bar' }, it will be returned as "{\"foo\" => \"bar\" }" as a string

CustomAudience created via API can't be displayed in Facebook Ad Manager


I am creating a FB Custom Audience. It works fine but if I go to the FB Ad Manager and open the Audience and try to edit it. I get an error saying that the audience was created via the API and it can not show the details. I have attached my code and the error.

This seems like its so fundamental and googling for it results in no results for me, that I think something must be wrong. Is it possible to make a custom audience via an API and then edit OR even just view the rule details via FB Ads Manager

rule = {"inclusions":
           "rules": [
                   {"type":"pixel","id": pixel_id}

audience = @ad_account.customaudiences.create({ name: "Test Audience",
                                                prefill: true,
                                                rule: rule})

The error message from Facebook Ads Manager when I open the custom audience and try to edit it:

This rule was created through API or third party applications. It contains syntax that we currently don't support in our interface.

load! is not supported for this object

Which SDK version are you using?


I am using facebookbusiness-

and when I try to get all actions for one account, I receive the next error.

Traceback (most recent call last):
4: from fb_ads.rb:49:in <main>' 3: from /usr/local/rvm/gems/ruby-2.5.1/gems/facebookbusiness- each'
2: from fb_ads.rb:54:in block in <main>' 1: from /usr/local/rvm/gems/ruby-2.5.1/gems/facebookbusiness- block in define_reader'
/usr/local/rvm/gems/ruby-2.5.1/gems/facebookbusiness- `load!': load! is not supported for this object (RuntimeError)

This is my code:

ad_account = FacebookAds::AdAccount.get('act_some_account_id')

ad_account.insights(fields: 'cpc,clicks,cost_per_conversion,ctr,impressions,reach,spend,actions',
time_range: "{'since':'2019-06-01','until':'2019-06-30'}",
).each do |insights|
ap insights.actions

but when I print only "insights",
I get:

:cpc => "177.813025",
:clicks => "9996",
:ctr => "2.209056",
:impressions => "452501",
:reach => "213311",
:spend => "1777419",
:actions => [
[ 0] {
:action_type => "onsite_conversion.messaging_first_reply",
:value => "1"
[ 1] {
:action_type => "onsite_conversion.messaging_conversation_started_7d",
:value => "1"

there is some wrong with my code?

thanks you,

AdImage IDs lead to invalid URI generation

AdImage IDs seem to consist of the account ID and the image hash with a colon as separator.
This leads to URI::InvalidURIError exceptions when trying to load the resource by its ID.

A minimum example:

image = FacebookAds::AdAccount.get('act_12345678').adimages.first
# => "feb391c9e7045348b52ef2081ed22830"

image.reload! # everything except the ID is cleared
#=> URI::InvalidURIError: bad URI(is not URI?): 12345678:feb391c9e7045348b52ef2081ed22830

Graph API needs to be upgraded to 4.0

Which SDK version are you using?


What's the issue?

Graph API v3.3 Will No Longer Be Supported

Steps/Sample code to reproduce the issue

Use any of the methods of the SDK and Facebook will throw this warning

Expected Results:

Graph API should be upgraded to 4.0

Ad Account end_advertiser parameter should accept string

When creating a new AdAccount on business, end_advertiser should be provided in string format. However, it is defined as object as you can see below:

This raises #<JSON::GeneratorError: only generation of JSON objects or arrays allowed> because lib/facebook_ads/field_types/object.rb tries to generate JSON from a string.

Example code used

@business = FacebookAds::Business.get("BUSINESS_ID", "name", MY_BUSINESS_MANAGER_ADMIN_ACCOUNT_SESSION)
@business.adaccount.create(name: "Test AdAccount", currency: "USD", end_advertiser: MY_APP_ID)

# JSON::GeneratorError: only generation of JSON objects or arrays allowed
# from /Users/premist/.gem/ruby/2.3.4/gems/json-1.8.6/lib/json/common.rb:223:in `generate'


Invalid parameter: Ambiguous Promoted Object Fields

I am getting this error, "Invalid parameter: Ambiguous Promoted Object Fields", when I try to create my ad. I have followed the code in the example you have provided. Here is my code for reference:

  #Create ad campaign
  campaign = ad_account.campaigns.create({
    name: params[:campaign_name],
    objective: 'LINK_CLICKS'

  #Create adsets
  ad_set = ad_account.adsets.create({
    name: 'Test ad set' ,
    bid_amount: 1000,
    billing_event: 'LINK_CLICKS',
    daily_budget: 15000, #params[:daily_budget],
    targeting: {
      age_max: params[:age_max],
      age_min: params[:age_min],
      geo_locations: {
        countries: [
      publisher_platforms: [
      facebook_positions: [
      instagram_positions: [
      device_platforms: [

  #Create ad
  ad ={
    status: 'PAUSED',
    name: 'Test ad set',
    creative: {
      object_story_spec: {
        page_id: page_id,
        link_data: {
          link: params[:link],
          message: params[:link_title],
          name: "Test",
          attachment_style: "link",
          call_to_action: {
            type: params[:call_to_action]
      title: 'Test title',
      body: 'Test body',
      object_url: params[:link],
      image_file: '/images/vynil.jpg'
    logo: '/images/vynil.jpg'

Thank you!

How to get 'X-FB-Ads-Insights-Throttle' header from response?

Trying to create a scheduled job to fetch insights from customer ad accounts but I need to constantly check the 'X-FB-Ads-Insights-Throttle' header in order to make sure Facebook doesn't limit me.

How can I check this header when calling the insights calls using the library?

`FacebookAds::ClientError: (#2) Service temporarily unavailable:`

Which SDK version are you using?


What's the issue?

Getting FacebookAds::ClientError: (#2) Service temporarily unavailable: on every request, not seeing any services/outages on their website?

Steps/Sample code to reproduce the issue

    @app_id = ENV.fetch('FACEBOOK_ACCOUNT_ID')
    @app_secret = ENV.fetch('FACEBOOK_APP_SECRET')
    @access_token = fetch_token

    puts @access_token

    @ad_account = FacebookAds::AdAccount.get("act_#{@app_id}",
                                             access_token: @access_token,
                                             app_secret: @app_secret)

    puts "Ad Account Name: #{}"

Observed Results:

fetch_token Prints an auth token correctly, which implies that the Account ID and Secret are correct.

the @ad_account call gets the error reported above

Expected Results:

the Ad Account name to be printed

Example code has incorrect syntax and won't parse

If you look at

locationss = page.locations({
you will see the example code throws an error:

 => #<FacebookAds::Page {:id=>"177231702648138"}> 
2.2.3 :037 > locationss = page.locations({
2.2.3 :038 >           fields: { 'location{latitude''longitude}''is_permanently_closed' },
2.2.3 :039 >           limit: '30000',
2.2.3 :040 >       })
SyntaxError: (irb):38: syntax error, unexpected '}', expecting =>

However, it appears that, perhaps, this code should be:

    locationss = page.locations({
      fields: [ 'location', 'is_permanently_closed' ],
      limit: '30000'

It looks like the fields value should be an array, with the values separated by commas and there should be no comma after limit since it is the last key-value pair in the hash. It's difficult to determine how to handle the location{latitude''longitude} part of the example as that also does not seem to be a valid syntax.

I'm not forking and attempting to fix this myself as I'm still trying to understand the correct syntax to make queries. For the record, back in May, I was able query the API successfully:

    006 >   page = FacebookAds::Page.get('125200950858892', "about,username,name,impressum,verification_status")
     => #<FacebookAds::Page {:id=>"125200950858892"}>
    007 > page.last_api_response
     => nil
    008 > page.attributes
     => {:id=>"125200950858892"}

    010 >   page.username
     => "BrandleSystem"
    012 > page.attributes
     => {:id=>"125200950858892", :about=>"Brandle® delivers social media security & brand protection.  It's the easiest way to Discover, Inventory, Monitor & Patrol your social presence!", :username=>"BrandleSystem", :name=>"Brandle", :verification_status=>"not_verified"}
    013 > page.last_api_response.headers["date"]
     => "Tue, 08 May 2018 03:19:12 GMT"

    015 >
     => "Brandle"
    017 > page.attributes
     => {:id=>"125200950858892", :about=>"Brandle® delivers social media security & brand protection.  It's the easiest way to Discover, Inventory, Monitor & Patrol your social presence!", :username=>"BrandleSystem", :name=>"Brandle", :verification_status=>"not_verified"}
    018 > page.last_api_response.headers["date"]
     => "Tue, 08 May 2018 03:20:02 GMT"

However now, with (the latest version I can actually seem to make work), the same queries throw errors:

2.2.3 :080 > page = FacebookAds::Page.get('125200950858892', ["about","username","name","impressum","verification_status"])
 => #<FacebookAds::Page {:id=>"125200950858892"}> 
2.2.3 :081 >
 => "125200950858892" 
2.2.3 :082 > page.attributes
 => {:id=>"125200950858892"} 
2.2.3 :083 > page = FacebookAds::Page.get('125200950858892', "about,username,name,impressum,verification_status")
 => #<FacebookAds::Page {:id=>"125200950858892"}> 
2.2.3 :084 > page.last_api_response
 => nil 
2.2.3 :085 > page.username
ArgumentError: wrong number of arguments (3 for 1..2)
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/response/logger.rb:7:in `initialize'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/middleware.rb:21:in `new'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/middleware.rb:21:in `new'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:48:in `build'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:162:in `block in to_app'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:162:in `each'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:162:in `inject'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:162:in `to_app'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:152:in `app'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:139:in `build_response'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/connection.rb:377:in `run_request'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/faraday-0.9.0/lib/faraday/connection.rb:140:in `get'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/facebookbusiness- `request'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/facebookbusiness- `execute_now'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/facebookbusiness- `execute'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/facebookbusiness- `block (2 levels) in <class:AdObject>'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/facebookbusiness- `load!'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/facebookbusiness- `block in define_reader'
	from (irb):85
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/railties- `start'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/railties- `start'
	from /Users/chip/.rvm/gems/ruby-2.2.3/gems/railties- `<top (required)>'
	from script/rails:6:in `require'
	from script/rails:6:in `<main>'2.2.3 :086 > 

v0.4.0.1 (+3 more versions) not published to Rubygems

Which SDK version are you using?


What's the issue?

ids_of_invalid_requests field missing on CheckBatchRequestStatus object

Steps/Sample code to reproduce the issue

> resp = catalog.check_batch_request_status(handle: "...handle here...", load_ids_of_invalid_requests: true)
> resp.first.handle
=> "...handle here..."
> resp.first.ids_of_invalid_requests
Traceback (most recent call last):
        1: from (irb):8
NoMethodError (undefined method `ids_of_invalid_requests' for #<FacebookAds::CheckBatchRequestStatus:0x0000...>)>

Observed Results:

Exception thrown for method not being defined in v0.3.3.3

Expected Results:

Being able to use v0.4.0.1 which has this method/field defined

Aside from filling out the issue template, my main concern is that facebookbusiness gem has not published a new version since v0.3.3.4:

whereas Github releases have 4 more versions released since then:

Is it possible that you can publish the missing releases to rubygems?

Thread Safety

The README has the following disclaimer:

We developed this SDK using Ruby 2.0, and supports Ruby 2.0+, however, the SDK is not thread-safe at the moment.

Is there a particular area of the SDK that isn't thread-safe that can be avoided? I see the with_session method definitely isn't; can we avoid some elements to utilize the library in threaded background workers now?

If not, what can be done to improve thread safety? Is it a matter of prioritization? Allocation of resources? Lack of interest?


DateTime format inconsistency


When we use the stats edge in AdsPixel (

has_edge :stats do |edge|
      edge.get 'AdsPixelStatsResult' do |api|
        api.has_param :aggregation, { enum: -> { AdsPixelStatsResult::AGGREGATION }}
        api.has_param :end_time, 'datetime'
        api.has_param :event, 'string'
        api.has_param :start_time, 'datetime'

It returns AdsPixelStatsResult and returned timestamp field(field :timestamp, 'datetime') is defined as datetime

When deserializing datetime (, it's expecting date time format like 2017-08-31T23:59:00-04:00 with time difference,

when String
            DateTime.strptime(value, '%FT%T%:z')

but for this case, returned datetime value is like 2017-08-16T14:00:00 without time difference.

IDName class is not autoloaded


Looks like there is some code to autoload all of the classes in facebook_ads/ad_objects/*. However, the class_name var set at line #69 does not work for the FacebookAds::IDName class because the capitalize transform matches IdName instead. We solved it locally by requiring that file directly:

require 'facebook_ads/ad_objects/id_name'

But, without that require statement, anything that references IDName fails.

Batch api does not return responses

Which SDK version are you using?

[7] pry(main)> FacebookAds::VERSION
=> ""
[11] pry(main)> RUBY_VERSION
=> "2.5.0"

What's the issue?

Batch API has the logic to return the response.
However, there is no return value because each_slice has been added.

def execute
return [] if operations.empty?
operations.each_slice(50) do |slice|
api_response =, '', session: session, params: batch_args(slice)).execute_now
self.last_api_response = api_response do |req, res|
next unless res
rescue APIError => e

Steps/Sample code to reproduce the issue

[4] pry(main)> require "facebookbusiness"
=> true
[5] pry(main)> session = access_token, app_secret: app_secret)
[6] pry(main)> batch = FacebookAds::Batch.with_batch do
  FacebookAds::AdAccount.get("act_#{ad_account_id}", session).name
[6] pry(main)* end 
[7] pry(main)> batch.execute
=> nil

Observed Results:

Enumerable#each_slice return nil.

Expected Results:

I added the map method.
It will be the expected result.

File: vendor/bundle/ruby/2.5.0/gems/facebookbusiness-
- 35:       operations.each_slice(50) do |slice|
+ 35:       operations.each_slice(50).map do |slice|
[6] pry(main)> batch.execute
=> [[#<FacebookAds::AdAccount {:id=>"act_****", :account_id=>"****"}>]]

Unable to set start_time and end_time

I am building a ROR app and trying to set start_time and end_time of an ad_set but it returns following exception.

FacebookAds::ClientError (Invalid parameter: Type Mismatch (fbtrace_id: HwzPJFp7o/8))

God knows how many formats i have tried.
following is my code
`ad_data["details"]["startDate"] = "2018-02-18T00:00:00"
ad_data["details"]["endDate"] = "2018-02-28T00:00:00"

	from_date =  DateTime.strptime(ad_data["details"]["startDate"], '%FT%T').to_time.utc.to_i
	end_date =  DateTime.strptime(ad_data["details"]["endDate"], '%FT%T').to_time.utc.to_i

	puts from_date
	adset = ad_account.adsets.create({
	    name: 'Test Ad Set',
	    bid_amount: 10,
	    billing_event: 'LINK_CLICKS',
	    daily_budget: 150000,
	    from_time: from_date

i have tried simple datetime string , DateTime Object, Time Object , Unix UTC etc.
I am new to ruby so excuse me if it's a code blunder.

JSON::GeneratorError:only generation of JSON objects or arrays allowed

I have set up a sandbox account and cannot create an ad, even after successfully obtaining the creative, adset, etc.


  1. FacebookAdsClient (development only tests) creates an ad
    adset_id: "120330000021336603",
    tracking_specs: "146149006094052",
    name: "Track this",
    creative: { creative_id: "120330000018226903" }

    only generation of JSON objects or arrays allowed
    /usr/local/rvm/gems/ruby-2.3.3/gems/json-1.8.6/lib/json/common.rb:223:in generate' /usr/local/rvm/gems/ruby-2.3.3/gems/json-1.8.6/lib/json/common.rb:223:in generate'
    /usr/local/rvm/gems/ruby-2.3.3/gems/facebookads- serialize' /usr/local/rvm/gems/ruby-2.3.3/gems/facebookads- block in to_params'
    /usr/local/rvm/gems/ruby-2.3.3/gems/facebookads- each' /usr/local/rvm/gems/ruby-2.3.3/gems/facebookads- map'
    /usr/local/rvm/gems/ruby-2.3.3/gems/facebookads- to_params' /usr/local/rvm/gems/ruby-2.3.3/gems/facebookads- create'
    ./lib/facebook_ads_client.rb:74:in `create_ad'

field :fields and def fields=(fields) mixing up


I've found issue in when using insights creation api.

def initialize(attributes, *args)
   self.fields = fields + attributes.keys

above self.fields is usually calling def fields=(fields) below when there are no field: fields declared.

But there is one place field: fields declared found below

so when it goes to

self.fields = fields + attributes.keys

it tries to access below method with name=fields instead of calling instance method fields=

 def define_writer(name)
    define_method("#{name}=") do |val|
       changes[name] = val

How to replicate this issue

FacebookAds::AdAccount.get('act_xxxxxx').insights(fields: 'ad_report_run').create(level: 'ad', fields: ['ad_id'])

This will throw exception
NoMethodError: undefined method `add' for nil:NilClass

Suggestion to fix

Just rename instance method def fields=(fields) to either def _fields=(fields) or more explicitly def response_fields=(fields)

DateTime woes

I think has some troubles. For once, it should refer to the global namespace object "::DateTime" instead of "DateTime", I guess this (at least) sometimes refers to FacebookAds::FieldTypes::DateTime instead.

Also, DateTime does not exists in stock ruby since 2.0, and requires active_support.

In any case, all my troubles went away when I added active_support, and monkeypatched FacebookAds::FieldTypes::DateTime as follows:

class FacebookAds::FieldTypes::DateTime
  def deserialize(value, session = nil)
    case value
      when String
        ::DateTime.strptime(value, "%FT%T%:z")

(Note: only needed reading from the API.)

Ad leads causes infinite loop

Calling FacebookAds::Ad.get(ad_id).leads.all when there are more than limit results causes infinite loop,
since response doesn't include pagination data.

Only solution seems to be to place large enough limit, but that is not very safe,
since API itself can limit the maximum number of results returned, which can again cause same infinite loop.

Using latest versions of gem and API, and 3.2.

Gem is making more calls than necessary

tl;dr there are 2 problems, Batch doesn't return a response with anything other than ids and the gem makes N requests for N attributes that are called on an object.


I'm creating many AdSets with FacebookAds::Batch.with_batch. When I do batch.execute, I get back only ids:

  #<FacebookAds::AdSet {:id=>\"some-id-1\"}>,
  #<FacebookAds::AdSet {:id=>\"some-id-2\"}>,
  #<FacebookAds::AdSet {:id=>\"some-id-3\"}>

I need to access its name and status (I want to double check that those were created correctly). When I do, it makes Request1:

Request GET

Calling object.first.status, another request is made:

Request GET

The diff is the fields at the end. That led me to just load those ids with ::FacebookAds::AdSet

The Problem

I want to load those records, so I do the following for each id:

::FacebookAds::AdSet.get('some-id-1', 'name,status,campaign_id', session)

That works, except that in reality I'm creating 3,000 ad sets for N customers. Facebook simply won't accept that many requests in serial. I tried using FacebookAds::Batch.with_batch to no avail.


  1. Is there a way to create records in a batch and get them back with all their attributes, not just id?
  2. Is there a way to call and have it request N attributes at once, instead of one call per attribute? This is very inconvenient.
  3. Is there a way to load N adsets by ids without making N requests?

Thanks a lot.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.