• Stars
    star
    1,240
  • Rank 37,884 (Top 0.8 %)
  • Language
    Python
  • License
    Other
  • Created about 10 years ago
  • Updated 7 months ago

Reviews

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

Repository Details

Python SDK for Meta Marketing APIs

Facebook Business SDK for Python

PyPI Build Status License

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.

Quick Start

Business SDK Getting Started Guide

Python is currently the most popular language for our third-party developers. facebook_business is a Python package that provides an interface between your Python application and Facebook's APIs within the Business SDK. This tutorial covers the basic knowledge needed to use the SDK and provides some exercises for the reader.

NOTE: facebook_business package is compatible with Python 2 and 3!

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

The easiest way to install the SDK is via pip in your shell.

NOTE: For Python 3, use pip3 and python3 instead.

NOTE: Use sudo if any of these complain about permissions. (This might happen if you are using a system installed Python.)

If you don't have pip:

easy_install pip

Now execute when you have pip:

pip install facebook_business

If you care for the latest version instead of a possibly outdated version in the pypi.python.org repository, check out the repository from GitHub or download a release tarball. Once you've got the package downloaded and unzipped, install it:

python setup.py install

Great, now you are ready to use the SDK!

Bootstrapping

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.):

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-page-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.

NOTE: We shall use the objects module throughout the rest of the tutorial. You can also use the individual class files under adobjects directly.

Understanding CRUD

The SDK implements a CRUD (create, read, update, delete) design. Objects relevant to exploring the graph are located in the objects module of the facebook_business package.

All objects on the graph are instances of AbstractObject. Some objects can be directly queried and thus are instances of AbstractCrudObject (a subclass of AbstractObject). Both these abstract classes are located in facebook_business.adobjects.

There is and additional folder adobjects under facebook_business. Under this you will see a file for every ad object in our Marketing API. These files are autogenerated from our API and therefore are close in parity with what API has to offer. Based on what CRUD operations can be performed on each object, you will see the presence of the following methods in them:

  • api_get
  • api_update
  • api_delete
  • create_xxx
  • get_xxx

For example, Campaign has all these methods but AdAccount does not. Read the Marketing API documentation for more information about how different ad objects are used.

There are some deprecated function in AbstractCrudObject, like

  • remote_create
  • remote_read
  • remote_update
  • remote_delete

Please try to stop use them since we may plan to deprecated them soon.

Exploring the Graph

The way the SDK abstracts the API is by defining classes that represent objects on the graph. These class definitions and their helpers are located in facebook_business.adobjects.

Initializing Objects

Look at AbstractObject's and AbstractCrudObject's __init__ method for more information. Most objects on the graph subclass from one of the two.

When instantiating an ad object, you can specify its id if it already exists by defining fbid argument. Also, if you want to interact with the API using a specific api object instead of the default, you can specify the api argument.

Edges

Look at the methods of an object to see what associations over which we can iterate. For example an AdUser object has a method get_ad_accounts which returns an iterator of AdAccount objects.

Ad Account

Most ad-related operations are in the context of an ad account. You can go to Ads Manager to see accounts for which you have permission. Most of you probably have a personal account.

Let's get all the ad accounts for the user with the given access token. I only have one account so the following is printed:

>>> me = adobjects.AdUser(fbid='me')
>>> my_accounts = list(me.get_ad_accounts())
>>> print(my_accounts)
[{   'account_id': u'17842443', 'id': u'act_17842443'}]
>>> type(my_accounts[0])
<class 'facebook_business.adobjects.AdAccount'>

WARNING: We do not specify a keyword argument api=api when instantiating the AdUser object here because we've already set the default api when bootstrapping.

NOTE: We wrap the return value of get_ad_accounts with list() because get_ad_accounts returns an EdgeIterator object (located in facebook_business.adobjects) and we want to get the full list right away instead of having the iterator lazily loading accounts.

For our purposes, we can just pick an account and do our experiments in its context:

>>> my_account = my_accounts[0]

Or if you already know your account id:

>>> my_account = adobjects.AdAccount('act_17842443')

Create

Let's create a campaign. It's in the context of the account, i.e. its parent should be the account.

fields = [
]
params = {
  adobjects.Campaign.Field.name : 'Conversions Campaign',
  adobjects.Campaign.Field.configured_status: adobjects.Campaign.Status.paused,
}
campaign = AdAccount(id).create_campaign(fields, params)

Then we specify some details about the campaign. To figure out what properties to define, you should look at the available fields of the object (located in Campaign.Field) and also look at the ad object's documentation (e.g. Campaign).

NOTE: To find out the fields, look at the individual class file under adobjects directory.

If there's an error, an exception will be raised. Possible exceptions and their descriptions are listed in facebook_business.exceptions.

Read

We can also read properties of an object from the api assuming that the object is already created and has a node path. Accessing properties of an object is simple since AbstractObject implements the collections.MutableMapping. You can access them just like accessing a key of a dictionary:

>>> print(my_account)
{'account_id': u'17842443', 'id': u'act_17842443'}
>>> my_account = my_account.api_get(fields=[adobjects.AdAccount.Field.amount_spent])
>>> print(my_account[adobjects.AdAccount.Field.amount_spent])
{'amount_spent': 21167, 'account_id': u'17842443', 'id': u'act_17842443'}

Update

To update an object, we can modify its properties and then call the api_update method to sync the object with the server. Let's correct the typo "Campain" to "Campaign":

>>> campaign.api_update(fields=[], params={adobjects.Campaign.Field.name:"Potato Campaign"})

You can see the results in ads manager.

Delete

If we decide we don't want the campaign we created anymore:

campaign.api_delete()

Useful Arguments

MULTIPLE ACCESS TOKENS

Throughout the docs, the method FacebookAdsApi.init is called before making any API calls. This method set up a default FacebookAdsApi object to be used everywhere. That simplifies the usage but it's not feasible when a system using the SDK will make calls on behalf of multiple users.

The reason why this is not feasible is because each user should have its own FacebookSession, with its own access token, rather than using the same session for every one. Each session should be used to create a separate FacebookAdsApi object. See example below:

my_app_id = '<APP_ID>'
my_app_secret = '<APP_SECRET>'
my_access_token_1 = '<ACCESS_TOKEN_1>'
my_access_token_2 = '<ACCESS_TOKEN_2>'
proxies = {'http': '<HTTP_PROXY>', 'https': '<HTTPS_PROXY>'} # add proxies if needed

session1 = FacebookSession(
    my_app_id,
    my_app_secret,
    my_access_token_1,
    proxies,
)

session2 = FacebookSession(
    my_app_id,
    my_app_secret,
    my_access_token_2,
    proxies,
)

api1 = FacebookAdsApi(session1)
api2 = FacebookAdsApi(session2)

In the SDK examples, we always set a single FacebookAdsApi object as the default one. However, working with multiples access_tokens, require us to use multiples apis. We may set a default api for a user, but, for the other users, we shall use its the api object as a param. In the example below, we create two AdUsers, the first one using the default api and the second one using its api object:

FacebookAdsApi.set_default_api(api1)

me1 = AdUser(fbid='me')
me2 = AdUser(fbid='me', api=api2)

Another way to create the same objects from above would be:

me1 = AdUser(fbid='me', api=api1)
me2 = AdUser(fbid='me', api=api2)

From here, all the following workflow for these objects remains the same. The only exceptions are the classmethods calls, where we now should pass the api we want to use as the last parameter on every call. For instance, a call to the Aduser.get_by_ids method should be like this:

session = FacebookSession(
 my_app_id,
 my_app_secret,
 my_access_token_1,
 proxies,
)

api = FacebookAdsApi(session1)
Aduser.get_by_ids(ids=['<UID_1>', '<UID_2>'], api=api)

CRUD

All CRUD calls support a params keyword argument which takes a dictionary mapping parameter names to values in case advanced modification is required. You can find the list of parameter names as attributes of {your object class}.Field. Under the Field class there may be other classes which contain, as attributes, valid fields of the value of one of the parent properties.

api_update and create_xxx support a files keyword argument which takes a dictionary mapping file reference names to binary opened file objects.

api_get supports a fields keyword argument which is a convenient way of specifying the 'fields' parameter. fields takes a list of fields which should be read during the call. The valid fields can be found as attributes of the class Field.

Edges

When initializing an EdgeIterator or when calling a method such as AdAccount.get_ad_campaigns:

  • You can specify a fields argument which takes a list of fields to read for the objects being read.
  • You can specify a params argument that can help you specify or filter the edge more precisely.

Batch Calling

It is efficient to group together large numbers of calls into one http request. The SDK makes this process simple. You can group together calls into an instance of FacebookAdsApiBatch (available in facebook_business.api). To easily get one for your api instance:

my_api_batch = api.new_batch()

Calls can be added to the batch instead of being executed immediately:

campaign.api_delete(batch=my_api_batch)

Once you're finished adding calls to the batch, you can send off the request:

my_api_batch.execute()

Please follow batch call guidelines in the Marketing API documentation. There are optimal numbers of calls per batch. In addition, you may need to watch out that for rate limiting as a batch call simply improves network performance and each call does count individually towards rate limiting.

Exceptions

See facebook_business.exceptions for a list of exceptions which may be thrown by the SDK.

Tests

Unit tests

The unit tests don't require an access token or network access. Run them with your default installed Python as follows:

python -m facebook_business.test.unit

You can also use tox to run the unit tests with multiple Python versions:

sudo apt-get install python-tox  # Debian/Ubuntu
sudo yum install python-tox      # Fedora
tox --skip-missing-interpreters

You can increase interpreter coverage by installing additional versions of Python. On Ubuntu you can use the deadsnakes PPA. On other distributions you can build from source and then use sudo make altinstall to avoid conflicts with your system-installed version.

Examples

Examples of usage are located in the examples/ folder.

Debug

If this SDK is not working as expected, it may be either a SDK issue or API issue.

This can be identified by constructing a raw cURL request and seeing if the response is as expected

for example:

from facebook_business.adobjects.page import Page
from facebook_business.api import FacebookAdsApi

FacebookAdsApi.init(access_token=access_token, debug=True)
page = Page(page_id).api_get(fields=fields,params=params)

When running this code, this cURL request will be printed to the console as:

curl -X 'GET' -H 'Accept: */*' -H 'Accept-Encoding: gzip, deflate' -H 'Connection: keep-alive' -H 'User-Agent: fbbizsdk-python-v3.3.1' 'https://graph.facebook.com/v3.3/<pageid>/?access_token=<access_token>&fields=name%2Cbirthday%2Cphone'

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.

Issue

Since we want to handle bugs more efficiently, we've decided to close issue reporting in Github and move to our dedicated bug reporting channel. If you encounter a bug with Business SDK (Python), please report the issue at our developer bug reporting channel.

License

Facebook Business SDK for Python 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

ThreatExchange

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

CacheLib

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

mariana-trench

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

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
65

transform360

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

openr

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

fboss

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

ktfmt

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

facebook-php-business-sdk

PHP SDK for Meta Marketing API
PHP
810
star
70

winterfell

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

pyre2

Python wrapper for RE2
C++
631
star
72

starlark-rust

A Rust implementation of the Starlark language
Rust
623
star
73

openbmc

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

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
75

time

Meta's Time libraries
Go
570
star
76

chef-cookbooks

Open source chef cookbooks.
Ruby
565
star
77

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
78

dotslash

Simplified executable deployment
Rust
523
star
79

Rapid

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

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
81

facebook-sdk-for-unity

The facebook sdk for unity.
C#
474
star
82

facebook-nodejs-business-sdk

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

FAI-PEP

Facebook AI Performance Evaluation Platform
Python
384
star
84

facebook-java-business-sdk

Java SDK for Meta Marketing APIs
Java
379
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