Facebook Business SDK for Ruby

repository·main·Indexed 42 days ago

https://github.com/facebook/facebook-ruby-business-sdk

A unified Ruby library that bundles multiple Facebook APIs, including Marketing, Pages, Business Manager, and Instagram. It provides a structured way to perform CRUD operations on API nodes, interact with edges, upload media, and use the Batch API. The SDK also includes a server-side client for the Conversions API with integration for the capi-param-builder to send web, app, and offline events to Meta.

Tokens
11.7K
Snippets
32
Records
39
Agent score
51%

What's inside Facebook Business SDK for Ruby

  1. Use the Batch API for multiple requests

    main

    The Batch API allows you to group multiple API calls into a single request to reduce latency. Wrap your operations in a FacebookAds::Batch.with_batch block and call .execute on the resulting batch object.

    Experimental: Dependencies within a batch You can create dependencies between requests using JSONPath references. For example, you can create a campaign and then immediately create an ad set that references that campaign's ID within the same batch block. The SDK handles the reference so the second request waits for the first to provide the ID.

    ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>')
    
    batch = FacebookAds::Batch.with_batch do
      10.times.map do |n|
        ad_account.campaigns.create({
          name: 'My Test Campaign #' + n,
          objective: 'CONVERSIONS',
          status: 'PAUSED',
        })
      end
    end
    
    batch.execute
    
    # Example with dependencies
    batch_with_deps = FacebookAds::Batch.with_batch do
      campaign = ad_account.campaigns.create({
        name: 'My Test Campaign',
        objective: 'CONVERSIONS',
        status: 'PAUSED',
      })
    
      ad_account.adsets.create({
        name: 'My AdSet',
        campaign_id: campaign.id, # Uses JSONPath reference internally
      })
    end
    batch_with_deps.execute
  2. Use the Conversions API

    main

    The SDK provides a server-side client to send web, app, and offline events to Meta. You construct UserData, CustomData, and Event objects, then execute them via an EventRequest.

    Conversions API Parameter Builder Integration

    The SDK integrates with the capi-param-builder to automatically fill in parameters like fbc, fbp, event_source_url, and referrer_url from an incoming HTTP request. Use event.set_request_context(request) to enable this. This is non-destructive; if you have already set a value, it will not be overwritten.

    require 'facebook_ads'
    
    FacebookAds.configure { |config| config.access_token = '<ACCESS_TOKEN>' }
    
    user_data = FacebookAds::ServerSide::UserData.new(
      email: 'joe@eg.com',
      client_ip_address: request.remote_ip,
      client_user_agent: request.user_agent
    )
    
    custom_data = FacebookAds::ServerSide::CustomData.new(
      currency: 'usd',
      value: 123.45
    )
    
    event = FacebookAds::ServerSide::Event.new(
      event_name: 'Purchase',
      event_time: Time.now.to_i,
      user_data: user_data,
      custom_data: custom_data,
      event_source_url: 'http://jaspers-market.com/product/123',
      action_source: 'website'
    )
    
    # Auto-fill parameters from the request context
    event.set_request_context(request)
    
    response = FacebookAds::ServerSide::EventRequest.new(
      pixel_id: '<PIXEL_ID>',
      events: [event]
    ).execute
    
    print "#{response}\n"
  3. Install the Facebook Business SDK for Ruby

    main

    The SDK is available as a RubyGem. You can install it via the command line or add it to your Gemfile.

    Command line installation:

    gem install facebookbusiness

    Gemfile usage:

    gem 'facebookbusiness'

    After installation, require the library in your code:

    require 'facebookbusiness'
  4. Configure Access Token and App Secret

    main

    The SDK supports three ways to configure your credentials:

    1. Global Configuration

    Use this if you are managing a single set of assets with one app/token. This sets a global state used across all requests.

    2. Environment Variables

    The SDK automatically picks up these variables as defaults:

    • FB_ACCESS_TOKEN
    • FB_APP_SECRET

    3. Session Objects or Instance Shortcuts

    For multi-tenant applications or when using different credentials for different objects, create a FacebookAds::Session or pass credentials directly during object instantiation.

    # Global configuration
    FacebookAds.configure do |config|
      config.access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
      config.app_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
    end
    
    # Using a Session object
    session = FacebookAds::Session.new(access_token: <ACCESS_TOKEN>, app_secret: <APP SECRET>)
    ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name', session)
    
    # Using a shortcut during instantiation
    ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name', {
        access_token: <ACCESS_TOKEN>, app_secret: <APP SECRET>
    })
  5. Configure Logging and API Debugging

    main

    You can configure the SDK to log HTTP requests and responses to help with debugging.

    FacebookAds.configure do |config|
      # Set up a logger
      config.logger = ::Logger.new(STDOUT).tap { |d| d.level = Logger::DEBUG }
    
      # Enable logging of API request and response bodies
      config.log_api_bodies = true
    end
  6. Install and use the Facebook Business SDK for Ruby

    main

    The Facebook Business SDK for Ruby is the primary entry point for interacting with Facebook Business APIs. To use the SDK, you must require the facebook_ads library, which is the core component loaded by the main facebookbusiness entry point.

    Note: The main entry point facebookbusiness.rb acts as a wrapper that requires the facebook_ads gem/library.

    require 'facebook_ads'
  7. Upload Images and Videos

    main

    To upload media, pass a Ruby File object as a parameter in the #create method of the appropriate edge.

    # Image upload (supports multiple images)
    ad_account.adimages.create({
      'logo1.png' => File.open('./assets/logo1.jpg'),
      'logo2.png' => File.open('./assets/logo2.jpg'),
    })
    
    # Video upload
    ad_account.advideos.create({
      name: 'My first video',
      source: File.open(File.expand_path("../video_ad_example.mp4", __FILE__))
    })
  8. Interact with Edges (GET, POST, DELETE)

    main

    Edges allow you to interact with related objects (e.g., campaigns belonging to an ad account).

    • Fetching (GET): Edges are Enumerable. You can iterate using #each or use methods like #map and #select.
    • Creating (POST): Use the #create method on the edge and pass a hash of parameters.
    • Removing (DELETE): Use the #destroy method on the edge, passing identifying parameters (like a hash).
    ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name')
    
    # Fetching edges
    ad_account.campaigns(fields: 'name').each do |campaign|
      puts campaign.name
    end
    
    # Creating a new node via an edge
    campaign = ad_account.campaigns.create({
      name: "My First campaign",
      objective: "CONVERSIONS",
    })
    
    # Removing from an edge
    ad_account.adimages.destroy({hash: 'abcd1234'})
  9. Perform Basic CRUD operations on nodes

    main

    The SDK uses auto-generated classes under the FacebookAds module for different API nodes (e.g., AdAccount, Campaign).

    Important Behavior: The #get method does not trigger an immediate API request. The GET request is fired on-demand when you access a specific attribute (lazy loading).

    • Read: Use .get(id, fields) to fetch a node.
    • Update: Modify attributes and call #save.
    • Delete: Call #destroy on the node instance.
    • Reload: Use #reload! to refresh the object from the API after changes.
    # Reading a node
    ad_account = FacebookAds::AdAccount.get('act_<YOUR_AD_ACCOUNT_ID>', 'name')
    puts ad_account.name # API request fires here
    
    # Updating a node
    ad_account.name = "New Ad Account"
    ad_account.save
    ad_account.reload!
    
    # Deleting a node
    campaign = FacebookAds::Campaign.get('<CAMPAIGN_ID>')
    campaign.destroy
  10. Perform API requests on edges

    main

    You can interact with related objects (edges) using the [verb]_edge methods (e.g., get_edge, post_edge, delete_edge). This allows you to perform operations on a specific path relative to the object's ID.

    # Example: Getting an edge (e.g., connections)
    connections = obj.get_edge('connections', params: { limit: 10 }) do |result|
      result
    end
    obj.get_edge('edge_name', params: {})
  11. Refresh object data with .load! and .reload!

    main

    If you need to synchronize the local object state with the server, use .load! or .reload!:

    • .load!: Fetches the current fields of the object from the Graph API and updates the local attributes.
    • .reload!: Resets the local object by deleting all attributes except for the id.
    # Refresh all current fields
    obj.load!
    
    # Reset object to only contain its ID
    obj.reload!
    obj.load!
    obj.reload!
  12. Manage AdAccountUserSettings

    main

    The AdAccountUserSettings class represents the user-specific settings and preferences for an Ad Account. It allows you to interact with various configuration fields such as column presets, export formats, and specific UI preferences like onboarding tour states or optimization guidance.

    Note: This class is auto-generated. For issues or feature requests, contact the Meta codegen framework team via GitHub; pull requests for this class are not accepted.