Facebook Business SDK for Python

repository·main·Indexed 23 days ago

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

A unified Python interface for multiple Facebook APIs, including the Marketing API, Pages, Business Manager, and Instagram. The SDK supports CRUD operations for Graph objects, batch calling for network efficiency, and server-side event transmission via the Conversions API.

Tokens
3.5K
Snippets
11
Records
17
Agent score
32%

What's inside facebook-python-business-sdk

  1. How CRUD operations work in the SDK

    main

    The SDK follows a CRUD (Create, Read, Update, Delete) design pattern. Most objects are instances of AbstractObject or AbstractCrudObject located in facebook_business.adobjects.

    Key methods available on many ad objects include:

    • api_get: Read properties from the API.
    • api_update: Sync local changes to the server.
    • api_delete: Remove the object.
    • create_xxx: Create a new instance of the object (e.g., create_campaign).
    • get_xxx: Retrieve related objects or edges.

    Note: Avoid using deprecated methods like remote_create, remote_read, remote_update, or remote_delete as they may be removed in future versions.

  2. Handle multiple access tokens with multiple FacebookAdsApi instances

    main

    While FacebookAdsApi.init sets a global default API object, it is not suitable for systems acting on behalf of multiple users. Instead, you should create a unique FacebookSession for each user's access token, and then create a separate FacebookAdsApi instance for each session.

    When working with multiple APIs, you can:

    1. Set one as the default using FacebookAdsApi.set_default_api(api) and pass specific api objects to other objects (e.g., AdUser(fbid='me', api=api2)).
    2. Explicitly pass the desired api instance to every object constructor or class method call.

    For class methods, you must pass the api instance as the last parameter.

    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>'}
    
    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)
    
    # Using different APIs for different objects
    FacebookAdsApi.set_default_api(api1)
    me1 = AdUser(fbid='me') # Uses default api1
    me2 = AdUser(fbid='me', api=api2) # Uses api2
    
    # Or passing api explicitly to class methods
    Aduser.get_by_ids(ids=['<UID_1>', '<UID_2>'], api=api1)
  3. Perform batch calling for efficiency

    main

    To improve network performance, you can group multiple API calls into a single HTTP request using FacebookAdsApiBatch.

    1. Create a batch instance from your API object using api.new_batch().
    2. Add calls to the batch by passing the batch instance to the batch parameter of an API method (e.g., campaign.api_delete(batch=my_api_batch)).
    3. Execute all queued calls using my_api_batch.execute().

    Note: Batching improves network performance but does not bypass rate limits; each call in a batch counts individually toward your rate limit.

    my_api_batch = api.new_batch()
    
    # Add calls to the batch instead of executing immediately
    campaign.api_delete(batch=my_api_batch)
    
    # Send the request
    my_api_batch.execute()
  4. Dynamic Products Update Example

    main

    This example demonstrates how to update specific products in a Facebook catalog by changing their price or marking them as out of stock. It is designed for users implementing Dynamic Product Ads (DPA) to keep their catalog synchronized with real-time changes like price fluctuations or stock availability.

    The workflow consists of three components:

    1. An XML product feed containing product data.
    2. A script (stock_update.py) that reads the feed and selects products for update (e.g., randomly choosing products to change price).
    3. A script (dpa_update.py) that uses the Ads API to apply those updates to the actual product catalog.

    Pre-requisites

    • A Facebook Business Manager account.
    • A product catalog already created and populated based on an XML feed.
    • Standard Facebook Python Ads SDK credentials (Access Token, etc.).
  5. How to run the Dynamic Products Update example

    main

    To execute the Dynamic Products Update demonstration, follow these steps:

    1. Prepare the Feed: Ensure your product feed has been created and the products are loaded into your catalog.
    2. Configure the Update Script: Open dpa_update.py and update the catalog_id variable with your actual Facebook Catalog ID.
    3. Execute the Pipeline: Run the following command in your terminal to select three products from the XML feed and pipe the results into the update script:
      python stock_update.py feed-dpa.xml 3 | python dpa_update.py
    4. Verify: Check the updated prices directly in your Facebook catalog to confirm the changes were applied.
    python stock_update.py feed-dpa.xml 3 | python dpa_update.py
  6. Auto-fill Conversions API parameters with set_request_context()

    main

    The SDK integrates with the Conversions API Parameter Builder to automatically populate event parameters (like fbc, fbp, referrer_url, etc.) from an incoming HTTP request.

    To use this, call .set_request_context(request) on your Event object. You can control which fields are auto-filled using the Preference object.

    Note: client_ip_address is not yet auto-derived in Python; you must continue to set it manually.

    from facebook_business.adobjects.serverside.preference import Preference
    
    event = Event(
        event_name='Purchase',
        event_time=int(time.time()),
        user_data=UserData(email='joe@eg.com'),
        action_source=ActionSource.WEBSITE,
    ).set_request_context(request)
    
    # Optional: gate which fields may be auto-filled (all default True).
    # Order: fbc, fbp, client_ip_address, referrer_url, event_source_url.
    #   .set_request_context(request, Preference(True, True, True, True, False))
  7. Bootstrap the SDK with API credentials

    main

    To use the SDK, you must initialize the FacebookAdsApi with your App ID, App Secret, and an Access Token. This sets the default API configuration for subsequent calls.

    import sys
    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'
    
    # Initialize the API
    FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)
    
    # Use an object (e.g., AdAccount)
    my_account = AdAccount('act_<your-adaccount-id>')
    campaigns = my_account.get_campaigns()
    print(campaigns)
  8. Debug API calls by printing cURL requests

    main

    To determine if an issue is with the SDK or the Meta API, you can enable debug mode in FacebookAdsApi.init. This will print the raw cURL request generated by the SDK to the console, allowing you to test the request manually.

    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)