Getting Started with the Facebook Business SDK

Prerequisites for Using the SDK

To get started with the Facebook Business SDK, complete the following prerequisite tasks:

1. Register as a Facebook developer.

If you don't have a Facebook developer account, create a one now.

Create Developer Account

2. Get an App ID for the app you are creating.

You get an App ID by creating a Facebook App entry on the App Dashboard. The App ID is a unique identifier that is used in API calls to differentiate your app from others.

Get your Facebook App ID or create a new one.

In most cases your app will need to go through App Review to acces the APIs of this SDK.


3. Get an App Secret.

The App Secret is a unique identifier associated with your application that authenticates requests made by your application to Facebook servers. Your App Secret should be treated like a password. For best practices on using and protecting App Secrets, see Login Security.

To generate an App Secret:

  1. Go to the App Dashboard and select your app.
  2. Open the Settings menu on the left and select Basic.
  3. Click the Show button. This displays your App Secret. Make a copy of it because it will be used when making API calls later.


4. Generate a User Access Token.

Graph API requires User Access Tokens. They are unique to each User and automatically expire in about an hour. You will use this User access token in a later step.

Please see the Common Scenarios Switching Access Tokens to learn how to exchange a User access token for a Page access token.

5. Create an Ad Account.

Visit the Ads Manager to create an account. An ad account will be automatically created for you if you do not have one already. Make a note of the Ad Account ID.

Learn more about ads and creating campaigns in our Ads Basics Guide.

Install and Configure the SDK

The instructions for installing and configuring vary based on the programming language used. Select your language from the list below for the implementation details.

Development Language:

Java

For Java development, you can use whatever development environment you like, as long as it supports Maven builds.

Add the Facebook Business SDK dependency to your Maven project.

Add the following XML code to the dependencies section of your pom.xml file:

<!-- https://mvnrepository.com/artifact/com.facebook.business.sdk/facebook-java-business-sdk -->
<dependency>
    <groupId>com.facebook.business.sdk</groupId>
    <artifactId>facebook-java-business-sdk</artifactId> 
    <version>[3.0.0,)</version>
</dependency>

Create a Java Class

Under src/main/java, create a Java class called TestFBJavaSDK, and add the following code:

In the code below, replace your-access-token, your-appsecret, and your-adaccount-id with your values.

import com.facebook.ads.sdk.APIContext;
import com.facebook.ads.sdk.APINodeList;
import com.facebook.ads.sdk.AdAccount;
import com.facebook.ads.sdk.Campaign;

public class TestFBJavaSDK
{
    public static final APIContext context = new APIContext(
            "your-access-token",
            "your-appsecret"
    );
    public static void main(String[] args)
    {
        AdAccount account = new AdAccount("act_{your-adaccount-id}", context);
        try {
            APINodeList<Campaign> campaigns = account.getCampaigns().requestAllFields().execute();
            for(Campaign campaign : campaigns) {
                System.out.println(campaign.getFieldName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }}

Test Your Install

Build and run your app. You should see the result in your console logging window. If it complains about an expired token, repeat the process for requesting a Page Access Token described in the prerequisites section above.

PHP

For PHP projects, the Facebook Business SDK can be installed using Composer. If you do not have it, you will need to install Composer before continuing.

Create a New Project Folder

Open a command terminal window and create a new folder for your project. When done, make it your current working directory. For example:

mkdir my_test_php_app
cd my_test_php_app

Install the Facebook Business SDK for PHP

Create composer.json with the following contents:

{
    "name": "name/my_test_php_app",
    "type": "project",
    "require": {
        "facebook/php-business-sdk": "^3.0.0"
    },
    "authors": [
        {
            "name": "Your Name",
            "email": "some@email.com"
        }
    ]
}

Install the SDK by running the following command in your terminal window:

composer install

Create a PHP File

Create a src/test.php file with the contents below:

In the code below, replace your-access-token, your-appsecret, and your-adaccount-id with your values.

<?php
require_once __DIR__ . '/../vendor/autoload.php';
use FacebookAds\Api;
use FacebookAds\Logger\CurlLogger;
use FacebookAds\Object\AdAccount;
use FacebookAds\Object\Campaign;
use FacebookAds\Object\Fields\CampaignFields;

$app_id = "{your-app-id}";
$app_secret = "{your-appsecret}";
$access_token = "{your-access-token}";
$account_id = "act_{your-adaccout-id}";

Api::init($app_id, $app_secret, $access_token);

$account = new AdAccount($account_id);
$cursor = $account->getCampaigns();

// Loop over objects
foreach ($cursor as $campaign) {
  echo $campaign->{CampaignFields::NAME}.PHP_EOL;
}

Test Your Install

Test your install with the following command:

php src/test.php

You should see the result in your terminal window. If it complains about an expired token, repeat the process for requesting a Page Access Token described in the prerequisites section above.

JavaScript (Node.js)

The Facebook Business SDK for JavaScript is distributed as a Node.js package. Install Node.js before continuing.

Create a New Project Folder

Open a command terminal window and create a new folder for your project. When done, make it your current working directory. For example:

mkdir my_test_nodejs_app
cd my_test_nodejs_app

Create, Configure, and Install

NPM is used to create and configure your project, and install your project dependencies. When the command is executed, it will prompt you for information about your project and, when complete, create a package.json file. Run the following command from your project folder in your terminal window:

npm init

You can update your configuration settings later by editing the package.json file directly.

Install the SDK package with the following command:

npm install --save facebook-nodejs-business-sdk

Modify Your Project Code

Open index.js and add the following code:

In the code below, replace your-access-token, and your-adaccount-id with your values.

const bizSdk = require('facebook-nodejs-business-sdk');

const accessToken = 'your-access-token';
const accountId = 'act_{your-adaccount-id}';

const FacebookAdsApi = bizSdk.FacebookAdsApi.init(accessToken);
const AdAccount = bizSdk.AdAccount;
const Campaign = bizSdk.Campaign;

const account = new AdAccount(accountId);
var campaigns;
    
account.read([AdAccount.Fields.name])
  .then((account) =>{
    return account.getCampaigns([Campaign.Fields.name], { limit: 10 }) // fields array and params
  })
  .then((result) =>{
    campaigns = result
    campaigns.forEach((campaign) =>console.log(campaign.name))  
  }).catch(console.error);

Test Your Install

Test your install with the following command:

node index.js

You should see the result in your terminal window. If it complains about an expired token, repeat the process for requesting a Page Access Token described in the prerequisites section above.

Python

The Facebook Business SDK for Python is distributed as a pypi module. If you have Python installed, it's likely that you already have the command line tool pip installed. If not, please install it from https://pip.pypa.io/en/stable/installing before continuing.

Install the SDK

Install the SDK globally with the following command:

[sudo] pip install facebook_business

Depends on your system, you may need to setup pyenv or use sudo at the beginning of the command for Linux/Unix-based systems if permission is denied when installing the SDK.

Create test.py

Create a test.py file with the contents below (assuming your system is using python 2.7 and installed under /opt/homebrew. Update to your proper python location.):

In the code below, replace your-app-id, your-access-token, your-appsecret, and your-adaccount-id with your values.

import sys
sys.path.append('/opt/homebrew/lib/python2.7/site-packages') # Replace this with the place you installed facebookads using pip
sys.path.append('/opt/homebrew/lib/python2.7/site-packages/facebook_business-3.0.0-py2.7.egg-info') # same as above

from facebook_business.api import FacebookAdsApi
from facebook_business.adobjects.adaccount import AdAccount

my_app_id = 'your-app-id'
my_app_secret = 'your-appsecret'
my_access_token = 'your-access-token'
FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
my_account = AdAccount('act_{your-adaccount-id}')
campaigns = my_account.get_campaigns()
print(campaigns)

Test Your Install

Test your install with the following command:

python test.py

You should see the result in your terminal window. If it complains about an expired token, repeat the process for requesting a Page Access Token described in the prerequisites section above.

Ruby

The Facebook Business SDK for Ruby is distributed as a RubyGems package. Install RubyGem before continuing.

Install the SDK

From a terminal window, run the following command from your project folder to install the Facebook Business SDK for Ruby. Depending on your environment, you may need to setup rbenv or rvm, or use sudo before the command.

gem install facebookbusiness

Create a Project File

Create a test.rb file with the contents below:

In the code below, replace your-access-token, your-appsecret, and your-adaccount-id with your values.

require 'facebookbusiness'
FacebookAds.configure do |config|
  config.access_token = 'your-access-token'
  config.app_secret = 'your-appsecret'
end

ad_account = FacebookAds::AdAccount.get('act_{your-adaccount-id}', 'name')
ad_account.campaigns(fields: 'name').each do |campaign|
  puts campaign.name
end

Test Your Install

Test your install with the following command:

ruby test.rb

You should see the result in your terminal window. If it complains about an expired token, repeat the process for requesting a Page Access Token described in the prerequisites section above.

GitHub Repositories

View the source code for the Business SDK at Github.

For Current Marketing SDK Users

To update to the Business SDK from the Marketing API follow the steps below.

Java

  • Update pom.xml
    • Update groupId from com.facebook.ads.sdk to com.facebook.business.sdk
    • Update artifactId from facebook-java-ads-sdk to facebook-java-business-sdk
    • Update version to v3.0.0

Nodejs

  • Update package.json
    • Remove facebook-nodejs-ads-sdk
    • Add facebook-nodejs-business-sdk:v3.0
  • If you have references to the package name facebook-nodejs-ads-sdk, such as require('facebook-nodejs-ads-sdk'), update it to facebook-nodejs-business-sdk
  • Run npm install

PHP

  • Update composer.json
    • Remove facebook-ads-sdk
    • Add facebook-business-sdk with version 3.0

Python

  • Run pip install facebook_business
  • Update all references to the namespace facebookads to facebook_business
  • If you have an .egg-info file, update it from facebookads-*.egg-info to the newly installed egg-info file such as facebook_business-*.egg-info

Ruby

  • Run gem install facebookbusiness
  • Update all references from require('facebook_ads') to require('facebookbusiness')