Upload Image for Ad Facebook Api Python
Facebook Business organisation SDK for Python
Introduction
The Facebook Business SDK is a one-finish store to assist our partners better serve their businesses. Partners are using multiple Facebook API's to server the needs of their clients. Adopting all these API'due south and keeping them up to appointment across the various platforms tin be fourth dimension consuming and ultimately prohibitive. For this reason Facebook has developed the Business organisation 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
Concern SDK Getting Started Guide
Python is currently the most popular language for our third party developers. facebook_business is a Python packet that provides an interface betwixt your Python application and Facebook's APIs within the Business SDK. This tutorial covers the basic knowledge needed to utilize the SDK and provide some exercises for the reader.
Note: facebook_business parcel is uniform with Python 2 and 3!
Pre-requisites
Annals An App
To get started with the SDK, you must take 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, information technology is recommended that yous turn on 'App Hush-hush Proof for Server API calls' in your app'southward Settings->Avant-garde 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 admission 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 admission token for your app and ask for the manage_page permission.
Refer to our Access Token Guide to learn more.
For at present, we can apply the Graph Explorer to get an access token.
Install bundle
The easiest way to install the SDK is via pip in your trounce.
NOTE: For Python 3, use pip3 and python3 instead.
NOTE: Employ sudo if any of these complain about permissions. (This might happen if you are using a organisation installed Python.)
If you don't have pip:
Now execute when y'all have pip:
pip install facebook_business If you care for the latest version instead of a perhaps outdated version in the pypi.python.org repository, check out the repository from GitHub or download a release tarball. In one case you've got the package downloaded and unzipped, install it:
Keen, now you are ready to utilise the SDK!
Bootstrapping
Create test.py
Create a test.py file with the contents below (bold your system is using python 2.vii 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-three.0.0-py2.7.egg-info') # same every bit 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-admission-token' FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token) my_account = AdAccount('act_<your-adaccount-id>') campaigns = my_account.get_campaigns() impress(campaigns) Test Your Install
Test your install with the following command:
You should see the result in your terminal window. If information technology complains about an expired token, repeat the process for requesting a Page Access Token described in the prerequisites section higher up.
NOTE: We shall utilize the objects module throughout the rest of the tutorial. Yous can also use the individual course files under adobjects direct.
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 packet.
All objects on the graph are instances of AbstractObject. Some objects can exist straight queried and thus are instances of AbstractCrudObject (a bracket of AbstractObject). Both these abstract classes are located in facebook_business.adobjects.
There is and boosted folder adobjects under facebook_business. Nether this yous volition see a file for every advertizement object in our Marketing API. These files are autogenerated from our API and therefore are close in parity with what API has to offering. Based on what Crud operations can be performed on each object, you will see the presence of the post-obit methods in them:
-
api_get -
api_update -
api_delete -
create_xxx -
get_xxx
For case, Campaign has all these methods simply AdAccount does not. Read the Marketing API documentation for more information about how different ad objects are used.
There are some deprecated part in AbstractCrudObject, like
-
remote_create -
remote_read -
remote_update -
remote_delete
Please try to cease utilize them since we may plan to deprecated them soon.
Exploring the Graph
The manner the SDK abstracts the API is by defining classes that stand for 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 data. Near objects on the graph subclass from one of the two.
When instantiating an advert object, yous can specify its id if it already exists past defining fbid statement. Too, if you lot desire to interact with the API using a specific api object instead of the default, y'all can specify the api argument.
Edges
Look at the methods of an object to come across 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 advertisement-related operations are in the context of an ad account. You tin can go to Ads Managing director to see accounts for which you have permission. Most of you probably have a personal account.
Permit's get all the advertizing 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()) >> > impress(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 statement api=api when instantiating the AdUser object here because we've already ready the default api when bootstrapping.
Notation: We wrap the return value of get_ad_accounts with list() considering get_ad_accounts returns an EdgeIterator object (located in facebook_business.adobjects) and nosotros want to get the full list right away instead of having the iterator lazily loading accounts.
For our purposes, nosotros can just pick an business relationship 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'southward in the context of the account, i.e. its parent should exist the account.
fields = [ ] params = { adobjects.Campaign.Field.proper noun : 'Conversions Campaign', adobjects.Campaign.Field.configured_status: adobjects.Campaign.Condition.paused, } campaign = AdAccount(id).create_campaign(fields, params) Then we specify some details virtually the campaign. To figure out what properties to define, y'all should look at the available fields of the object (located in Campaign.Field) and as well look at the ad object's documentation (e.thou. Campaign).
NOTE: To find out the fields, look at the individual course 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
Nosotros tin can also read backdrop of an object from the api assuming that the object is already created and has a node path. Accessing backdrop of an object is simple since AbstractObject implements the collections.MutableMapping. You tin 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. Permit's correct the typo "Campain" to "Campaign":
>> > campaign.api_update(fields =[], params ={adobjects.Campaign.Field.name:"Potato Entrada"}) You can see the results in ads manager.
Delete
If nosotros decide we don't want the campaign we created anymore:
Useful Arguments
MULTIPLE ACCESS TOKENS
Throughout the docs, the method FacebookAdsApi.init is chosen earlier making any API calls. This method prepare a default FacebookAdsApi object to be used everywhere. That simplifies the usage just it'south not viable when a system using the SDK will make calls on behalf of multiple users.
The reason why this is non feasible is because each user should take its own FacebookSession, with its ain access token, rather than using the same session for every one. Each session should be used to create a split 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. Nosotros may gear up a default api for a user, just, for the other users, nosotros shall use its the api object as a param. In the example below, nosotros 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 mode to create the aforementioned objects from above would be:
me1 = AdUser(fbid = 'me', api = api1) me2 = AdUser(fbid = 'me', api = api2) From hither, 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 exist similar 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 statement which takes a dictionary mapping parameter names to values in case avant-garde modification is required. You tin can notice the list of parameter names as attributes of {your object class}.Field. Nether the Field form in that location may be other classes which contain, as attributes, valid fields of the value of one of the parent properties.
api_update and create_xxx back up a files keyword statement 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 form Field.
Edges
When initializing an EdgeIterator or when calling a method such as AdAccount.get_ad_campaigns:
- You tin can specify a
fieldsargument which takes a list of fields to read for the objects beingness read. - You can specify a
paramsstatement that can assistance 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 tin can group together calls into an instance of FacebookAdsApiBatch (available in facebook_business.api). To easily get one for your api case:
my_api_batch = api.new_batch() Calls tin can be added to the batch instead of being executed immediately:
campaign.api_delete(batch = my_api_batch) Once you lot're finished calculation calls to the batch, y'all can send off the asking:
Please follow batch phone call guidelines in the Marketing API documentation. At that place are optimal numbers of calls per batch. In improver, you may need to watch out that for charge per unit limiting every bit a batch phone call simply improves network functioning and each phone call does count individually towards rate limiting.
Exceptions
See facebook_business.exceptions for a list of exceptions which may exist thrown by the SDK.
Tests
Unit tests
The unit tests don't require an access token or network admission. Run them with your default installed Python every bit follows:
python -one thousand facebook_business.test.unit of measurement Yous can also apply 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 tin increase interpreter coverage by installing additional versions of Python. On Ubuntu you can use the deadsnakes PPA. On other distributions you lot can build from source and then utilise sudo brand altinstall to avoid conflicts with your arrangement-installed version.
Examples
Examples of usage are located in the examples/ folder.
Debug
If this SDK is not working equally expected, it may be either a SDK effect or API issue.
This can be identified past constructing a raw curlicue request and seeing if the response is every bit expected
for case:
from facebook_business.adobjects.folio import Page from facebook_business.api import FacebookAdsApi FacebookAdsApi.init(access_token = access_token, debug = True) page = Folio(page_id).api_get(fields = fields,params = params) When running this code, this curlicue request will be printed to the console as:
ringlet -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.three/<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 motility to our defended bug reporting channel. If you lot see a bug with Business SDK (Python), please report the result at our developer bug reporting channel.
License
Facebook Business organization SDK for Python is licensed nether the LICENSE file in the root directory of this source tree.
Source: https://github.com/facebook/facebook-python-business-sdk
0 Response to "Upload Image for Ad Facebook Api Python"
Post a Comment