• Stars
    star
    379
  • Rank 113,004 (Top 3 %)
  • Language
    Java
  • License
    Other
  • Created about 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Java SDK for Meta Marketing APIs

Facebook Business SDK for Java

Maven Central License Build Status

Introduction

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.

facebook-java-business-sdk is a Java library that provides an interface between your Java application and Facebook's Graph API. This tutorial covers the basics, including examples, needed to use the SDK.

Quick Start

Business SDK Getting Started Guide

Pre-requisites

Register An App

To get started with the SDK, you must have an app registered on developers.facebook.com.

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.

Install package

To start using Java SDK, follow the instructions on Getting started instruction.

If you want to use pre-compiled .jar file, visit https://repo1.maven.org/maven2/com/facebook/business/sdk/facebook-java-business-sdk/ to download specific version. If you download the one without dependencies, you will need to download all dependent .jar files and add them to your path when build and run. Use the .pom file in the version directory to decide dependencies.

Run Sample code

Here is the minimal code needed to create a campaign in your ad account. If your app and build environments are set up correctly, this code should compile and run without error. You can verify the created campaign in Ads Manager.

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();
    }
  }
}

More examples can be found in the /examples folder.

Local Build and Test

To locally modify this package and use the updated package in your project, please follow these steps:

  • Clone or download the source code and import it into your favorite IDE
  • Make the necessary modifications
  • Remove the maven-gpg-plugin defined in the pom.xml
  • Build the modified package and install it in the local Maven repository by executing the following Maven command mvn clean install. A JAR file will be created and installed in your local directory (typically located in the .m2 folder).
  • Update your project's pom.xml to reference the locally modified version of the package in case you changed the business SDK package version
  • Build your own project and test

Understanding the Business SDK

Please see the Business SDK Documentation for more information about implementation and common scenarios. The Business SDK is consistent with v3.0 endpoints related to Pages, Business Manager, Instagram and Marketing products. Please refer to APIs within the Business SDK to get the list of APIs that are within the Business SDK.

Get an object

You always need to create an APIContext before making any API calls. APIContext includes your access token and app secret:

APIContext context = new APIContext(ACCESS_TOKEN, APP_SECRET);

To fetch a campaign object:

Campaign campaign = new Campaign(CAMPAIGN_ID, context); // this only creates a new empty object
campaign = campaign.get().requestAllFields().execute();
// 1. get() is the API call name to get the object;
// 2. requestAllFields() means you want all the fields. If you only want certain fields, then you can call requestXXXFields() instead, and sever response will only contain specified fields.
// 3. ***IMPORTANT*** any API calls should end with execute(), otherwise it will not be executed.

Or, you can use an equivalent shortcut:

Campaign campaign = Campaign.fetchById(CAMPAIGN_ID, context);

After fetching the object, you can read the data inside:

String id = campaign.getFieldId();
String name = campaign.getFieldName();
// Note that the methods to read field data are getFieldXXX(). This is to distinguish method names of field data from method names of API GET calls.

Update and Delete

Update:

campaign.update()
        .setName("Updated Java SDK Test Campaign") // set parameter for the API call
        .execute();

Delete:

campaign.delete().execute();

Edge Read and Write (Create Object)

Edge is a relational concept in Graph API.

For example, if you want to know all the campaigns under an ad account, then you call GET on the campaigns edge from the ad account object.

Or, if you want to create a new campaign under this account, then you call POST (create) on the campaigns edge of ad account.

Read:

AdAccount account = new AdAccount(ACCOUNT_ID, context);
APINodeList<Campaign> campaigns = account.getCampaigns().requestAllFields().execute();
for(Campaign campaign : campaigns) {
	System.out.println(campaign.getFieldName());
}

** Important **: Handling pagination: Most edge APIs have default pagination, which returns a limited number of objects (~30 objects) instead of the entire list. If you want to load more, you need to make a separate API call. In our SDK, you can call to nextPage():

campaigns = campaigns.nextPage();
  • Or, enable auto pagination iterator with:
campaigns = campaigns.withAutoPaginationIterator(true);

In this case, campaigns.iterator() will return an iterator that can fetch the next page automatically.

// Enhanced for loop
for(Campaign campaign : campaigns) {
	System.out.println(campaign.getFieldName());
}

// Foreach with lambda is also supported
campaigns.forEach(campaign -> System.out.println(campaign.getFieldName()));

// Note: APIException will be wrapped in a Runtime exception

To fetch all campaigns in your account.

With auto pagination iterator, next page will be fetched automatically in enhanced for loop and foreach loop. In this scenario, campaign.size(), campaign.get(i) is no longer reliable and shouldn't be used

Write (create object):

Most objects are under ad account. So you may always want to try account.createXXX() to create an object.

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();
// The create call only returns id of the new object.
// So you want to fetch() to get all the data of the object.
// fetch() is just another shortcut for
// campaign = campaign.get().requestAllFields().execute();
campaign.fetch();

Batch Mode

Every execute() is an HTTP request, which takes a network round trip. Facebook API does support batch mode, which allows you to make multiple API calls in a single HTTP request.

In this SDK, you can simply replace execute() with addToBatch() to prepare a batch API call. When it's ready, you call batch.execute().

Example:

      BatchRequest batch = new BatchRequest(context);
      account.createCampaign()
        .setName("Java SDK Batch Test Campaign")
        .setObjective(Campaign.EnumObjective.VALUE_LINK_CLICKS)
        .setSpendCap(10000L)
        .setStatus(Campaign.EnumStatus.VALUE_PAUSED)
        .addToBatch(batch, "campaignRequest");
      account.createAdSet()
        .setName("Java SDK Batch Test AdSet")
        .setCampaignId("{result=campaignRequest:$.id}")
        .setStatus(AdSet.EnumStatus.VALUE_PAUSED)
        .setBillingEvent(AdSet.EnumBillingEvent.VALUE_IMPRESSIONS)
        .setDailyBudget(1000L)
        .setBidAmount(100L)
        .setOptimizationGoal(AdSet.EnumOptimizationGoal.VALUE_IMPRESSIONS)
        .setTargeting(targeting)
        .addToBatch(batch, "adsetRequest");
      account.createAdImage()
        .addUploadFile("file", imageFile)
        .addToBatch(batch, "imageRequest");
      account.createAdCreative()
        .setTitle("Java SDK Batch Test Creative")
        .setBody("Java SDK Batch Test Creative")
        .setImageHash("{result=imageRequest:$.images.*.hash}")
        .setLinkUrl("www.facebook.com")
        .setObjectUrl("www.facebook.com")
        .addToBatch(batch, "creativeRequest");
      account.createAd()
        .setName("Java SDK Batch Test ad")
        .setAdsetId("{result=adsetRequest:$.id}")
        .setCreative("{creative_id:{result=creativeRequest:$.id}}")
        .setStatus("PAUSED")
        .setBidAmount(100L)
        .addToBatch(batch);
      List<APIResponse> responses = batch.execute();
      // responses contains the result of each API call in order. However, if the API calls have dependency, then some result could be null.

Error Handling

Currently all the errors are wrapped in APIException and its subclasses.

MalformedResponseException is caused by the improper parsing of a server response (likely a bug in the SDK).

FailedRequestException is caused by either a client error or server failure. See details in the next section.

We have a plan to improve this by adding more details and providing a convenient function to get the error code.

Customization and Debugging

Enable debugging

You can enable the debug output by setting the APIContext to debug mode:

public static final APIContext context = new APIContext(ACCESS_TOKEN, APP_SECRET).enableDebug(true).setLogger(System.out);

This will print out the network requests and responses. By default it prints on STDOUT, but you can customize by calling .setLogger(PrintSteam)

Customize Network

In v0.2.0, we added APIRequest.changeRequestExecutor(IRequestExecutor), which can be used to set your own network request executor. This makes it possible to add proxy settings, automatic retry, or better network traffic management. See /example/NetworkCustomizationExample.java.

Currently this is a static method because it is likely to be a global setting. If you do think object-level Customization is needed, we'll add that functionality.

The executor needs to implement IRequestExecutor interface:

    public static interface IRequestExecutor {
        public String execute(String method, String apiUrl, Map<String, Object> allParams, APIContext context) throws APIException, IOException;
        public String sendGet(String apiUrl, Map<String, Object> allParams, APIContext context) throws APIException, IOException;
        public String sendPost(String apiUrl, Map<String, Object> allParams, APIContext context) throws APIException, IOException;
        public String sendDelete(String apiUrl, Map<String, Object> allParams, APIContext context) throws APIException, IOException;
    }

DefaultRequestExecutor is used by default, and it is also a good starting point for Customization.

Missing or Incorrect Request Params/Fields

It is recommended to use setXXX() or requestXXXField() to construct a proper APIRequest, which prevents mis-spelling of parameter/field names. However, if you believe that some needed params/fields are missing from these methods, you can call:

    APIRequest.setParam(param, value)
    APIRequest.setParam.requestField(field, true)

This also works if you believe the type of the param is not correct in SDK.

In this case, please help us make improvement by filing issues.

Missing Fields in Class Definition

If you believe that certain fields are returned from server, but they are missing in class definition, then you can still access those fields by fetching it from raw response:

campaign.getRawResponseAsJsonObject().get("field").getAsString();

This situation can occasionally happen if new fields are added to serve response while SDK is not up-to-date. We'll update the SDK periodically to include new fields.

Ad-hoc APIRequest

Most of Marketing API can be found in SDK classes. If you don't find the one you want to access, it is possible to construct an Ad-hoc APIRequest:

    APIRequest<AdAccount> request = new APIRequest<AdAccount>(context, "me", "/adaccounts", "GET", AdAccount.getParser());
    APINodeList<AdAccount> accounts = (APINodeList<AdAccount>)(request.execute());

When constructing the APIRequest, you need to provide

  • APIContext, which has the access token,
  • The node ID, which is typically a long number, but it can also be some alias, like "me",
  • The edge name, which should start with "/"; if it's for a Node API, then use "/"
  • The HTTP Method, GET/POST/DELETE
  • The parser for the expected response type. You can use null if it is not in the SDK, which will return APINodeList when executed.

FailedRequestException Troubleshooting

There are many possible causes for a failed request:

  • Incorrect parameters are provided in the API request (check Graph API Docs)
  • Permission issue (check your access token or app secret)
  • SDK bug (report on Github)
  • Temporary network issue (check your network and retry)
  • Temporary server issue (retry, or report on Facebook Platform Bugs if it happens too often)
  • Server bug (report on Facebook Platform Bugs)

As the first step of troubleshooting, please enable debugging in the APIContext.

Here are some hints on troubleshooting:

  • If it's caused by incorrect parameters, you'll see error descriptions in the exception message.
  • If it's caused by permission issue, you'll see error message like "permission denied" or "unknown path"
  • If in stack trace you see that the failed request is caused by exceptions such as NullPointerException or MalformedResponseException, it is likely a SDK bug (or your own bug, depending on the stacktrace).
  • If you see in the debug message that the params sent to server don't match what you specified, it is possible that you didn't specify the param correctly, or SDK didn't assemble the request properly.
  • For temporary server issue, typically retry should work after a few seconds.
  • If server persistently responds with "Unknown error," then it is potentially server bug.

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.

License

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

More Repositories

1

react

The library for web and native user interfaces.
JavaScript
227,971
star
2

react-native

A framework for building native applications using React
C++
118,682
star
3

create-react-app

Set up a modern web app by running one command.
JavaScript
101,913
star
4

docusaurus

Easy to maintain open source documentation websites.
TypeScript
56,059
star
5

jest

Delightful JavaScript Testing.
TypeScript
41,554
star
6

rocksdb

A library that provides an embeddable, persistent key-value store for fast storage.
C++
28,328
star
7

folly

An open-source C++ library developed and used at Facebook.
C++
27,122
star
8

zstd

Zstandard - Fast real-time compression algorithm
C
22,448
star
9

flow

Adds static typing to JavaScript to improve developer productivity and code quality.
OCaml
22,068
star
10

lexical

Lexical is an extensible text editor framework that provides excellent reliability, accessibility and performance.
TypeScript
19,616
star
11

relay

Relay is a JavaScript framework for building data-driven React applications.
Rust
18,191
star
12

hhvm

A virtual machine for executing programs written in Hack.
Hack
18,048
star
13

prophet

Tool for producing high quality forecasts for time series data that has multiple seasonality with linear or non-linear growth.
Python
17,943
star
14

fresco

An Android library for managing images and the memory they use.
Java
17,041
star
15

yoga

Yoga is an embeddable layout engine targeting web standards.
C++
16,928
star
16

infer

A static analyzer for Java, C, C++, and Objective-C
OCaml
14,715
star
17

flipper

A desktop debugging platform for mobile developers.
TypeScript
13,221
star
18

watchman

Watches files and records, or triggers actions, when they change.
C++
12,294
star
19

react-devtools

An extension that allows inspection of React component hierarchy in the Chrome and Firefox Developer Tools.
11,030
star
20

hermes

A JavaScript engine optimized for running React Native.
C++
9,388
star
21

jscodeshift

A JavaScript codemod toolkit.
JavaScript
9,270
star
22

chisel

Chisel is a collection of LLDB commands to assist debugging iOS apps.
Python
9,090
star
23

buck

A fast build system that encourages the creation of small, reusable modules over a variety of platforms and languages.
Java
8,568
star
24

stylex

StyleX is the styling system for ambitious user interfaces.
JavaScript
8,333
star
25

proxygen

A collection of C++ HTTP libraries including an easy to use HTTP server.
C++
8,026
star
26

facebook-ios-sdk

Used to integrate the Facebook Platform with your iOS & tvOS apps.
Swift
7,720
star
27

litho

A declarative framework for building efficient UIs on Android.
Java
7,646
star
28

pyre-check

Performant type-checking for python.
OCaml
6,696
star
29

facebook-android-sdk

Used to integrate Android apps with Facebook Platform.
Kotlin
6,066
star
30

redex

A bytecode optimizer for Android apps
C++
5,991
star
31

sapling

A Scalable, User-Friendly Source Control System.
Rust
5,815
star
32

componentkit

A React-inspired view framework for iOS.
Objective-C++
5,746
star
33

fishhook

A library that enables dynamically rebinding symbols in Mach-O binaries running on iOS.
C
5,117
star
34

PathPicker

PathPicker accepts a wide range of input -- output from git commands, grep results, searches -- pretty much anything. After parsing the input, PathPicker presents you with a nice UI to select which files you're interested in. After that you can open them in your favorite editor or execute arbitrary commands.
Python
5,075
star
35

metro

🚇 The JavaScript bundler for React Native
JavaScript
5,061
star
36

prop-types

Runtime type checking for React props and similar objects
JavaScript
4,446
star
37

idb

idb is a flexible command line interface for automating iOS simulators and devices
Objective-C
4,431
star
38

Haxl

A Haskell library that simplifies access to remote data, such as databases or web-based services.
Haskell
4,227
star
39

FBRetainCycleDetector

iOS library to help detecting retain cycles in runtime.
Objective-C++
4,190
star
40

memlab

A framework for finding JavaScript memory leaks and analyzing heap snapshots
TypeScript
4,187
star
41

duckling

Language, engine, and tooling for expressing, testing, and evaluating composable language rules on input strings.
Haskell
4,021
star
42

fbt

A JavaScript Internationalization Framework
JavaScript
3,849
star
43

regenerator

Source transformer enabling ECMAScript 6 generator functions in JavaScript-of-today.
JavaScript
3,817
star
44

buck2

Build system, successor to Buck
Rust
3,307
star
45

mcrouter

Mcrouter is a memcached protocol router for scaling memcached deployments.
C++
3,222
star
46

wangle

Wangle is a framework providing a set of common client/server abstractions for building services in a consistent, modular, and composable way.
C++
3,030
star
47

react-strict-dom

React Strict DOM (RSD) is a subset of React DOM, imperative DOM, and CSS that supports web and native targets
JavaScript
2,922
star
48

wdt

Warp speed Data Transfer (WDT) is an embeddedable library (and command line tool) aiming to transfer data between 2 systems as fast as possible over multiple TCP paths.
C++
2,836
star
49

igl

Intermediate Graphics Library (IGL) is a cross-platform library that commands the GPU. It provides a single low-level cross-platform interface on top of various graphics APIs (e.g. OpenGL, Metal and Vulkan).
C++
2,719
star
50

fbthrift

Facebook's branch of Apache Thrift, including a new C++ server.
C++
2,535
star
51

mysql-5.6

Facebook's branch of the Oracle MySQL database. This includes MyRocks.
C++
2,446
star
52

Ax

Adaptive Experimentation Platform
Python
2,272
star
53

fbjs

A collection of utility libraries used by other Meta JS projects.
JavaScript
1,953
star
54

jsx

The JSX specification is a XML-like syntax extension to ECMAScript.
HTML
1,945
star
55

react-native-website

The React Native website and docs
JavaScript
1,899
star
56

screenshot-tests-for-android

Generate fast deterministic screenshots during Android instrumentation tests
Java
1,733
star
57

idx

Library for accessing arbitrarily nested, possibly nullable properties on a JavaScript object.
JavaScript
1,686
star
58

TextLayoutBuilder

An Android library that allows you to build text layouts more easily.
Java
1,470
star
59

mvfst

An implementation of the QUIC transport protocol.
C++
1,433
star
60

SoLoader

Native code loader for Android
Java
1,300
star
61

facebook-python-business-sdk

Python SDK for Meta Marketing APIs
Python
1,240
star
62

ThreatExchange

Trust & Safety tools for working together to fight digital harms.
C++
1,170
star
63

CacheLib

Pluggable in-process caching engine to build and scale high performance services
C++
1,097
star
64

mariana-trench

A security focused static analysis tool for Android and Java applications.
C++
1,041
star
65

fatal

Fatal is a library for fast prototyping software in modern C++. It provides facilities to enhance the expressive power of C++. The library is heavily based on template meta-programming, while keeping the complexity under-the-hood.
C++
1,000
star
66

transform360

Transform360 is an equirectangular to cubemap transform for 360 video.
C
996
star
67

openr

Distributed platform for building autonomic network functions.
C++
883
star
68

fboss

Facebook Open Switching System Software for controlling network switches.
C++
851
star
69

ktfmt

A program that reformats Kotlin source code to comply with the common community standard for Kotlin code conventions.
Kotlin
818
star
70

facebook-php-business-sdk

PHP SDK for Meta Marketing API
PHP
810
star
71

winterfell

A STARK prover and verifier for arbitrary computations
Rust
728
star
72

pyre2

Python wrapper for RE2
C++
631
star
73

starlark-rust

A Rust implementation of the Starlark language
Rust
623
star
74

openbmc

OpenBMC is an open software framework to build a complete Linux image for a Board Management Controller (BMC).
C
615
star
75

SPARTA

SPARTA is a library of software components specially designed for building high-performance static analyzers based on the theory of Abstract Interpretation.
C++
609
star
76

time

Meta's Time libraries
Go
570
star
77

chef-cookbooks

Open source chef cookbooks.
Ruby
565
star
78

IT-CPE

Meta's Client Platform Engineering tools. Some of the tools we have written to help manage our fleet of client systems.
Ruby
554
star
79

dotslash

Simplified executable deployment
Rust
523
star
80

Rapid

The OpenStreetMap editor driven by open data, AI, and supercharged features
JavaScript
515
star
81

lexical-ios

Lexical iOS is an extensible text editor framework that integrates the APIs and philosophies from Lexical Web with a Swift API built on top of TextKit.
Swift
477
star
82

facebook-sdk-for-unity

The facebook sdk for unity.
C#
474
star
83

facebook-nodejs-business-sdk

Node.js SDK for Meta Marketing APIs
JavaScript
469
star
84

FAI-PEP

Facebook AI Performance Evaluation Platform
Python
384
star
85

chef-utils

Utilities related to Chef
Ruby
290
star
86

opaque-ke

An implementation of the OPAQUE password-authenticated key exchange protocol
Rust
275
star
87

dns

Collection of Meta's DNS Libraries
Go
257
star
88

facebook360_dep

Facebook360 Depth Estimation Pipeline - https://facebook.github.io/facebook360_dep
HTML
241
star
89

akd

An implementation of an auditable key directory
Rust
219
star
90

tac_plus

A Tacacs+ Daemon tested on Linux (CentOS) to run AAA via TACACS+ Protocol via IPv4 and IPv6.
C
207
star
91

facebook-ruby-business-sdk

Ruby SDK for Meta Marketing API
Ruby
204
star
92

usort

Safe, minimal import sorting for Python projects.
Python
171
star
93

grocery-delivery

The Grocery Delivery utility for managing cookbook uploads to distributed Chef backends.
Ruby
153
star
94

taste-tester

Software to manage a chef-zero instance and use it to test changes on production servers.
Ruby
146
star
95

TestSlide

A Python test framework
Python
143
star
96

sapp

Post Processor for Facebook Static Analysis Tools.
Python
127
star
97

homebrew-fb

OS X Homebrew formulas to install Meta open source software
Ruby
124
star
98

threat-research

Welcome to the Meta Threat Research Indicator Repository, a dedicated resource for the sharing of Indicators of Compromise (IOCs) and other threat indicators with the external research community
Python
124
star
99

ocamlrep

Sets of libraries and tools to write applications and libraries mixing OCaml and Rust. These libraries will help keeping your types and data structures synchronized, and enable seamless exchange between OCaml and Rust
Rust
121
star
100

squangle

SQuangLe is a C++ API for accessing MySQL servers
C++
121
star