Facebook Business SDK for Java

repository·main·Indexed 19 days ago

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

A unified Java interface for interacting with Facebook Graph API services, including the Marketing API, Pages API, Business Manager, and Instagram. The SDK supports managing ad campaigns, handling pagination via APINodeList, utilizing BatchRequest for multiple requests, and implementing the Conversions API for server-side event delivery.

Tokens
3.9K
Snippets
14
Records
16
Agent score
16%

What's inside facebook-java-business-sdk

  1. Read and Write via Edges (Create Objects)

    main

    Edges represent relationships in the Graph API.

    Reading Edges: Use the getter for the edge (e.g., account.getCampaigns()) to retrieve a list of related objects.

    Writing Edges: To create a new object under a parent, use the createXXX() method on the parent object (e.g., account.createCampaign()).

    Note on Creation: The create call typically only returns the ID of the new object. To populate the object with data, call .fetch() immediately after.

    // Reading an edge
    AdAccount account = new AdAccount(ACCOUNT_ID, context);
    APINodeList<Campaign> campaigns = account.getCampaigns().requestAllFields().execute();
    
    // Writing (creating) an object via an edge
    Campaign campaign = account.createCampaign()
            .setName("Java SDK Test Campaign")
            .setObjective(Campaign.EnumObjective.VALUE_LINK_CLICKS)
            .execute();
    
    // Fetch the newly created object to get its full data
    campaign.fetch();
  2. Build the SDK from source locally

    main

    To modify the SDK and use your changes in a local project:

    1. Clone or download the source code and import it into your IDE.
    2. Make your modifications.
    3. Remove the maven-gpg-plugin defined in the pom.xml.
    4. Build and install the package to your local Maven repository using:
      mvn clean install
    5. Update your own project's pom.xml to reference your locally modified version (ensure the version number matches if you changed it).
    mvn clean install
  3. Handle pagination in APINodeList

    main

    Most edge APIs return a limited number of objects (approx. 30). To access subsequent pages, you can either manually call .nextPage() or enable the auto-pagination iterator.

    When using withAutoPaginationIterator(true), the iterator() or enhanced for-loops will automatically fetch new pages. Warning: When auto-pagination is enabled, methods like campaigns.size() and campaigns.get(i) are no longer reliable.

    // Manual pagination
    campaigns = campaigns.nextPage();
    
    // Auto pagination
    campaigns = campaigns.withAutoPaginationIterator(true);
    for(Campaign campaign : campaigns) {
        System.out.println(campaign.getFieldName());
    }
  4. Auto-fill event parameters with Conversions API Parameter Builder

    main

    The SDK includes the Conversions API Parameter Builder to automatically populate event parameters from an incoming HTTP request. By calling setRequestContext(request) on an Event object, the SDK can auto-fill fields like user_data.fbc, user_data.fbp, event_source_url, and referrer_url if they are left empty.

    Key behaviors:

    • Non-destructive: If you manually set a value, the auto-filler will not overwrite it.
    • Gated: You can control which fields are allowed to be auto-filled using a Preference object.
    • Limitation: In Java, client_ip_address is not yet auto-derived; you must continue to set client_ip_address and client_user_agent manually.
    // Basic usage with auto-fill
    Event event = new Event()
        .eventName("Purchase")
        .eventTime(System.currentTimeMillis() / 1000L)
        .userData(new UserData().email("joe@eg.com"))
        .actionSource(ActionSource.website)
        .setRequestContext(request);
    
    // Advanced usage: gating which fields may be auto-filled
    // Order of Preference arguments: fbc, fbp, client_ip_address, referrer_url, event_source_url.
    // Example: allow everything except event_source_url
    // .setRequestContext(request, new Preference(true, true, true, true, false));
  5. Use Batch Mode for multiple requests

    main

    To reduce network round trips, use BatchRequest to group multiple API calls into a single HTTP request. Instead of calling .execute(), use .addToBatch(batch, "identifier") for each request. Finally, call batch.execute() to send the entire batch.

    BatchRequest batch = new BatchRequest(context);
    
    account.createCampaign()
        .setName("Batch Campaign")
        .addToBatch(batch, "campaignRequest");
    
    account.createAdSet()
        .setName("Batch AdSet")
        .setCampaignId("{result=campaignRequest:$.id}")
        .addToBatch(batch, "adsetRequest");
    
    List<APIResponse> responses = batch.execute();
  6. Install the Facebook Business SDK for Java

    main

    You can install the SDK using Maven or by downloading pre-compiled .jar files.

    Use Maven Central to manage the dependency in your pom.xml.

    Manual JAR Installation

    If you download a pre-compiled .jar file from Maven Central, ensure you also download all required dependent .jar files. You can use the .pom file located in the version directory to identify the necessary dependencies.

  7. Update and Delete objects

    main

    To modify an existing object, use the .update() method followed by the desired setters and .execute(). To remove an object, use .delete().execute().

    // Update
    campaign.update()
            .setName("Updated Java SDK Test Campaign")
            .execute();
    
    // Delete
    campaign.delete().execute();
  8. Configure Facebook App and Access Tokens

    main

    Before using the SDK, you must complete the following setup on the Facebook Developer Portal:

    1. Register an App: Create an app at developers.facebook.com.
    2. Add Marketing API: For Marketing API functionality, go to your App Dashboard and add the Marketing API product.
    3. Security Recommendation: Enable 'App Secret Proof for Server API calls' in your app's Settings -> Advanced page.
    4. Obtain Access Token:
      • Use the Graph Explorer to generate a token for testing.
      • For Marketing API, generate a User access token with the ads_management permission.
      • For Pages API, generate a Page access token with the manage_page permission.
  9. Fetch an object using the SDK

    main

    To retrieve an object (e.g., a Campaign), you can either instantiate the object with the ID and context and then call .get(), or use the fetchById shortcut.

    Important: All API calls must end with .execute() to be sent to the server. Use .requestAllFields() to get all available data, or .requestXXXFields() to specify a subset of fields.

    // Method 1: Manual instantiation and execution
    Campaign campaign = new Campaign(CAMPAIGN_ID, context);
    campaign = campaign.get().requestAllFields().execute();
    
    // Method 2: Shortcut
    Campaign campaign = Campaign.fetchById(CAMPAIGN_ID, context);
  10. Create a campaign using the Java SDK

    main

    This example demonstrates the minimal code required to create a campaign in an ad account using APIContext, AdAccount, and Campaign classes.

    import com.facebook.ads.sdk.APIContext;
    import com.facebook.ads.sdk.AdAccount;
    import com.facebook.ads.sdk.AdAccount.EnumCampaignStatus;
    import com.facebook.ads.sdk.AdAccount.EnumCampaignObjective;
    import com.facebook.ads.sdk.Campaign;
    import com.facebook.ads.sdk.APIException;
    
    public class QuickStartExample {
    
      public static final String ACCESS_TOKEN = "[Your access token]";
      public static final Long ACCOUNT_ID = [Your account ID];
      public static final String APP_SECRET = "[Your app secret]";
    
      public static final APIContext context = new APIContext(ACCESS_TOKEN, APP_SECRET);
      public static void main(String[] args) {
        try {
          AdAccount account = new AdAccount(ACCOUNT_ID, context);
          Campaign campaign = account.createCampaign()
            .setName("Java SDK Test Campaign")
            .setObjective(Campaign.EnumObjective.VALUE_LINK_CLICKS)
            .setSpendCap(10000L)
            .setStatus(Campaign.EnumStatus.VALUE_PAUSED)
            .execute();
          System.out.println(campaign.fetch());
        } catch (APIException e) {
          e.printStackTrace();
        }
      }
    }