### Create and Retrieve Campaign Example Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/ad-objects-reference.md An example demonstrating how to create a new campaign and then retrieve its details. ```APIDOC ## Create and Retrieve Campaign Example ### Description This example shows the process of creating a new campaign with specified parameters and then fetching its details. ### Example ```python from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.campaign import Campaign account = AdAccount('act_1234567890') # Create campaign campaign = account.create_campaign( fields=[], params={ Campaign.Field.name: 'Summer Sale Campaign', Campaign.Field.objective: Campaign.Objective.conversions, Campaign.Field.status: Campaign.Status.paused, Campaign.Field.daily_budget: 100000 # $1000 } ) print(f"Created campaign: {campaign.get(Campaign.Field.id)}") # Retrieve it campaign = Campaign(campaign.get(Campaign.Field.id)) campaign.api_get(fields=[Campaign.Field.name, Campaign.Field.daily_budget]) print(f"Budget: ${campaign[Campaign.Field.daily_budget] / 100}") ``` ``` -------------------------------- ### Install pip using easy_install Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/README.md Use this command if pip is not already installed on your system. ```shell easy_install pip ``` -------------------------------- ### Create and Execute a Simple Batch Request Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/configuration.md Use batch requests for efficient bulk operations. This example demonstrates creating a new batch and adding a simple GET request without specific callback handlers. ```python from facebook_business.api import FacebookAdsApi api = FacebookAdsApi.init( access_token='YOUR_TOKEN' ) # Simple batch with no callbacks batch = api.new_batch() ``` -------------------------------- ### Install Facebook Python Business SDK from source Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/README.md Install the SDK by downloading and building it from the source code repository. ```shell python setup.py install ``` -------------------------------- ### Set Referrer URL Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md Example of setting the referrer URL. ```python event = Event(event_name='Purchase', event_time=1234567890, referrer_url='https://www.google.com') ``` -------------------------------- ### Install Facebook Python Business SDK using pip Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/README.md Install the SDK using pip for easy integration into your Python projects. ```shell pip install facebook_business ``` -------------------------------- ### Install Tox for Multi-Version Testing Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/README.md Install tox on Debian/Ubuntu or Fedora systems to run unit tests across multiple Python versions. Ensure tox is installed before running. ```bash sudo apt-get install python-tox # Debian/Ubuntu ``` ```bash sudo yum install python-tox # Fedora ``` ```bash tox --skip-missing-interpreters ``` -------------------------------- ### Request Statistics Example Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api.md An example demonstrating how to retrieve the number of API requests attempted and succeeded. ```APIDOC ## Request Statistics Example ```python from facebook_business.api import FacebookAdsApi api = FacebookAdsApi.get_default_api() # Make some API calls # ... attempts = api.get_num_requests_attempted() successes = api.get_num_requests_succeeded() print(f"Attempted: {attempts}, Succeeded: {successes}") ``` ``` -------------------------------- ### Test SDK Installation Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/README.md Run this command in your terminal to verify your Facebook Python Business SDK installation. If you encounter an expired token error, re-authenticate as per the prerequisites. ```python python test.py ``` -------------------------------- ### Set Event Source URL Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md Example of setting the source URL where the event occurred. ```python event = Event(event_name='Purchase', event_time=1234567890, event_source_url='https://www.example.com/page') ``` -------------------------------- ### ViewContent Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Example of a ViewContent event with product details such as name, category, IDs, type, value, and currency. ```APIDOC ## ViewContent Event ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( content_name='iPhone 15 Pro', content_category='Electronics > Mobile Phones', content_ids=['IPHONE-15-PRO-128GB'], content_type='product', value=999.99, currency='USD' ) event = Event( event_name='ViewContent', event_time=1234567890, custom_data=custom_data ) ``` ``` -------------------------------- ### FacebookAdsApi Constructor Example Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api.md Demonstrates how to initialize a FacebookAdsApi instance with a FacebookSession. Use this to set up your API client with authentication and specify the Graph API version and debug logging. ```python from facebook_business.session import FacebookSession from facebook_business.api import FacebookAdsApi session = FacebookSession( app_id='YOUR_APP_ID', app_secret='YOUR_APP_SECRET', access_token='YOUR_ACCESS_TOKEN' ) api = FacebookAdsApi(session, api_version='v20.0', enable_debug_logger=True) ``` -------------------------------- ### Send a Batch of Multiple Events Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event-request.md This example shows how to create and send a batch of multiple events, including PageView, ViewContent, AddToCart, and Purchase. Each event is constructed with relevant user and custom data. ```python import time from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.action_source import ActionSource events = [] # Event 1: Page view events.append(Event( event_name='PageView', event_time=int(time.time()) - 3600, action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), event_source_url='https://example.com/products' )) # Event 2: View content events.append(Event( event_name='ViewContent', event_time=int(time.time()) - 1800, action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), custom_data=CustomData(value=99.99, currency='USD', content_name='Product X'), event_source_url='https://example.com/product/x' )) # Event 3: Add to cart events.append(Event( event_name='AddToCart', event_time=int(time.time()) - 900, action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), custom_data=CustomData(value=99.99, currency='USD'), event_source_url='https://example.com/cart' )) # Event 4: Purchase events.append(Event( event_name='Purchase', event_time=int(time.time()), event_id='order_12345', action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), custom_data=CustomData(value=99.99, currency='USD'), event_source_url='https://example.com/checkout/confirmation' )) request = EventRequest(pixel_id='123456789', events=events) response = request.execute() print(f"Received: {response['events_received']}, Total sent: {len(events)}") ``` -------------------------------- ### Configure Event Request Context with Preference Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/types.md Example of creating a Preference object to selectively auto-fill user data fields and applying it to an event's request context. This example demonstrates how to disable auto-filling of URLs. ```python from facebook_business.adobjects.serverside.preference import Preference from facebook_business.adobjects.serverside.event import Event # Only auto-fill FBC and FBP, not URLs preference = Preference( enable_fbc=True, enable_fbp=True, enable_referrer_url=False, enable_event_source_url=False ) event = Event( event_name='Purchase', event_time=1234567890 ).set_request_context(request, preference) ``` -------------------------------- ### Add GET, POST, and DELETE requests to a batch Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api-batch.md Demonstrates how to add different types of HTTP requests (GET, POST, DELETE) to a batch object. Each request can specify its method, relative path, and parameters. The batch is then executed to send all requests in one go. ```python from facebook_business.api import FacebookAdsApi api = FacebookAdsApi.get_default_api() batch = api.new_batch() # Add GET request to batch batch.add( 'GET', ('me', 'adaccounts'), params={'fields': 'id,name,account_status'} ) # Add POST request to batch batch.add( 'POST', ('act_1234567890', 'campaigns'), params={ 'name': 'Batch Campaign', 'status': 'PAUSED', 'objective': 'CONVERSIONS' } ) # Add DELETE request to batch batch.add( 'DELETE', ('123456789012', 'campaigns', '987654321') ) # Execute all requests responses = batch.execute() ``` -------------------------------- ### Example cURL Request for Debugging Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/README.md This is an example of a cURL request that the SDK might generate when debugging is enabled. It shows the HTTP method, headers, and URL for a page data retrieval. ```bash 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//?access_token=&fields=name%2Cbirthday%2Cphone' ``` -------------------------------- ### Simple Purchase Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Example of creating a Purchase event with basic custom data including value and currency. ```APIDOC ## Simple Purchase Event ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( value=149.99, currency='USD' ) event = Event( event_name='Purchase', event_time=1234567890, custom_data=custom_data ) ``` ``` -------------------------------- ### Initialize Facebook SDK and Conversions API Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/configuration.md Standard initialization of the Facebook SDK is required before using the Conversions API. This example shows basic initialization and then setting up an event request. ```python from facebook_business.api import FacebookAdsApi # Standard initialization FacebookAdsApi.init(access_token='YOUR_ACCESS_TOKEN') # Use Conversions API from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.event_request import EventRequest event = Event(event_name='Purchase', event_time=1234567890) request = EventRequest(pixel_id='YOUR_PIXEL_ID', events=[event]) response = request.execute() ``` -------------------------------- ### Sending Events with EventRequest Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event-request.md This example demonstrates how to create an EventRequest object with shared user data and multiple events, then execute it. ```APIDOC ## Sending Events with EventRequest ### Description This example demonstrates how to create an EventRequest object with shared user data and multiple events, then execute it. ### Method ```python request.execute() ``` ### Parameters This method does not take any parameters directly, but the `EventRequest` object is configured with: - `pixel_id`: The ID of the Facebook Pixel. - `events`: A list of `Event` objects to be sent. - `user_data`: A `UserData` object containing information shared across all events. ### Request Example ```python from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.adobjects.serverside.user_data import UserData # User data shared across all events in request shared_user_data = UserData(email='customer@example.com') events = [ Event(event_name='PageView', event_time=123456789), Event(event_name='ViewContent', event_time=123456790), Event(event_name='AddToCart', event_time=123456791) ] request = EventRequest( pixel_id='123456789', events=events, user_data=shared_user_data ) response = request.execute() ``` ### Response #### Success Response (200) Indicates that the events were successfully received by the server. #### Response Example ```json { "events_received": 3 } ``` ``` -------------------------------- ### Content IDs and Catalog Example Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Illustrates how to specify product identifiers from various sources using the `content_ids` field, including SKUs, GTINs, and Meta catalog product IDs. ```APIDOC ## Content IDs and Catalog The `content_ids` field allows specifying product identifiers from multiple sources: ```python custom_data = CustomData( value=199.99, currency='USD', content_ids=[ 'SKU-ABC-123', # Your internal SKU 'GTIN-12345678901234', # Global Trade Item Number 'CATALOG-ID-567' # Meta catalog product ID ], content_type='product' ) ``` ``` -------------------------------- ### Simple Batch Operations Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api-batch.md Demonstrates how to queue multiple read operations (GET requests) into a single batch and execute them, then process the responses. ```APIDOC ## Simple Batch Operations This example shows how to create a batch of read operations and execute them. ```python from facebook_business.api import FacebookAdsApi from facebook_business.adobjects.campaign import Campaign api = FacebookAdsApi.init( app_id='YOUR_APP_ID', app_secret='YOUR_APP_SECRET', access_token='YOUR_ACCESS_TOKEN', account_id='act_1234567890' ) batch = api.new_batch() # Batch multiple read operations batch.add('GET', ('act_1234567890', 'campaigns'), params={'limit': 10}) batch.add('GET', ('act_1234567890', 'ads'), params={'limit': 10}) batch.add('GET', ('act_1234567890', 'adsets'), params={'limit': 10}) responses = batch.execute() for i, response in enumerate(responses): if response.is_success(): print(f"Request {i}: {response.json()}") else: print(f"Request {i} failed: {response.error()}") ``` ``` -------------------------------- ### Send Events with Request Options Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event-request.md Customize event requests by providing RequestOptions. This example sets the 'log_event_source' to 'automated_system'. ```python from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.adobjects.serverside.request_options import RequestOptions request_options = RequestOptions() request_options.log_event_source = 'automated_system' request = EventRequest(pixel_id='123456789', events=events) response = request.execute(request_options) ``` -------------------------------- ### Multiple Events in Batch Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md This example demonstrates how to send multiple events (PageView, AddToCart, Purchase) in a single request to the Conversions API for efficiency. ```APIDOC ## Multiple Events in Batch This example demonstrates how to send multiple events (PageView, AddToCart, Purchase) in a single request to the Conversions API for efficiency. ```python import time from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.action_source import ActionSource from facebook_business.adobjects.serverside.event_request import EventRequest events = [] # Event 1: Page view events.append(Event( event_name='PageView', event_time=int(time.time()) - 3600, action_source=ActionSource.WEBSITE, user_data=UserData(email='user1@example.com'), event_source_url='https://example.com/products' )) # Event 2: Add to cart events.append(Event( event_name='AddToCart', event_time=int(time.time()) - 1800, action_source=ActionSource.WEBSITE, user_data=UserData(email='user1@example.com'), custom_data=CustomData(value=29.99, currency='USD'), event_source_url='https://example.com/product/jacket' )) # Event 3: Purchase events.append(Event( event_name='Purchase', event_time=int(time.time()), action_source=ActionSource.WEBSITE, user_data=UserData(email='user1@example.com'), custom_data=CustomData(value=29.99, currency='USD'), event_id='purchase_001', event_source_url='https://example.com/checkout/confirmation' )) # Send all events in single request request = EventRequest(pixel_id='YOUR_PIXEL_ID', events=events) response = request.execute() ``` ``` -------------------------------- ### Batch of Multiple Events Example Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event-request.md Shows how to send multiple events in a single request. This is efficient for sending a series of user interactions that occur in sequence. ```APIDOC ## Batch of Multiple Events ```python import time from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.action_source import ActionSource events = [] # Event 1: Page view events.append(Event( event_name='PageView', event_time=int(time.time()) - 3600, action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), event_source_url='https://example.com/products' )) # Event 2: View content events.append(Event( event_name='ViewContent', event_time=int(time.time()) - 1800, action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), custom_data=CustomData(value=99.99, currency='USD', content_name='Product X'), event_source_url='https://example.com/product/x' )) # Event 3: Add to cart events.append(Event( event_name='AddToCart', event_time=int(time.time()) - 900, action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), custom_data=CustomData(value=99.99, currency='USD'), event_source_url='https://example.com/cart' )) # Event 4: Purchase events.append(Event( event_name='Purchase', event_time=int(time.time()), event_id='order_12345', action_source=ActionSource.WEBSITE, user_data=UserData(email='user@example.com'), custom_data=CustomData(value=99.99, currency='USD'), event_source_url='https://example.com/checkout/confirmation' )) request = EventRequest(pixel_id='123456789', events=events) response = request.execute() print(f"Received: {response['events_received']}, Total sent: {len(events)}") ``` ``` -------------------------------- ### Create AdSet Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/ad-objects-reference.md Example of creating a new ad set associated with a campaign. Specifies targeting, budget, optimization goals, and status. Ensure the parent Campaign object is initialized. ```python from facebook_business.adobjects.campaign import Campaign from facebook_business.adobjects.adset import AdSet campaign = Campaign('123456789') # Create ad set adset = campaign.create_adset( fields=[], params={ AdSet.Field.name: 'US Targeting', AdSet.Field.optimization_goal: AdSet.OptimizationGoal.link_clicks, AdSet.Field.billing_event: AdSet.BillingEvent.impressions, AdSet.Field.daily_budget: 50000, AdSet.Field.status: AdSet.Status.paused, AdSet.Field.targeting: { 'age_min': 25, 'age_max': 45, 'geo_locations': { 'regions': [{'key': 'US'}] } } } ) ``` -------------------------------- ### AddToCart Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Example of an AddToCart event with product details including name, category, IDs, type, and quantity. ```APIDOC ## AddToCart Event ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( value=89.99, currency='USD', content_name='Leather Jacket', content_category='Clothing > Outerwear', content_ids=['SKU-JAK-001'], content_type='product', num_items=1 ) event = Event( event_name='AddToCart', event_time=1234567890, custom_data=custom_data ) ``` ``` -------------------------------- ### Create Ad Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/ad-objects-reference.md Example of creating a new ad associated with an ad set. Specifies the ad name, status, and links to a pre-created creative. Ensure the parent AdSet object is initialized. ```python from facebook_business.adobjects.adset import AdSet from facebook_business.adobjects.ad import Ad adset = AdSet('1234567890') # Create ad ad = adset.create_ad( fields=[], params={ Ad.Field.name: 'My Ad', Ad.Field.adset_id: adset.get(Ad.Field.id), Ad.Field.status: Ad.Status.paused, Ad.Field.creative: { 'creative_id': '9876543210' # Pre-created creative } } ) ``` -------------------------------- ### Basic Purchase Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md This example demonstrates how to create and send a single 'Purchase' event to the Conversions API, including user data, custom purchase data, and event details. ```APIDOC ## Basic Purchase Event This example demonstrates how to create and send a single 'Purchase' event to the Conversions API, including user data, custom purchase data, and event details. ```python import time from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.action_source import ActionSource from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.api import FacebookAdsApi FacebookAdsApi.init(access_token='YOUR_ACCESS_TOKEN') # Create user data user_data = UserData( email='customer@example.com', phone='14155551234', # Format: country code + number (no special chars) first_name='John', last_name='Doe', city='Menlo Park', state='CA', country_code='US', zip_code='94025' ) # Create custom data with purchase info custom_data = CustomData( value=142.52, currency='USD', content_name='Leather Jacket', content_type='product', content_id='product_123', num_items=1 ) # Create event event = Event( event_name='Purchase', event_time=int(time.time()), event_id='event_' + str(int(time.time() * 1000)), user_data=user_data, custom_data=custom_data, event_source_url='https://example.com/checkout/confirmation', action_source=ActionSource.WEBSITE ) # Send event request = EventRequest( pixel_id='YOUR_PIXEL_ID', events=[event] ) response = request.execute() print(response) ``` ``` -------------------------------- ### Product Purchase with Details Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Example of a Purchase event with detailed product information such as content name, category, IDs, type, number of items, and order ID. ```APIDOC ## Product Purchase with Details ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( value=299.99, currency='USD', content_name='Sony WH-1000XM4 Headphones', content_category='Electronics > Audio', content_ids=['SKU-12345', 'GTIN-567890123456'], content_type='product', num_items=1, order_id='ORDER-20240101-001' ) event = Event( event_name='Purchase', event_time=1234567890, custom_data=custom_data ) ``` ``` -------------------------------- ### AddToCart Event with Request Context Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md This example shows how to send an 'AddToCart' event and includes setting the request context, which is useful when integrating with web frameworks like Django. ```APIDOC ## AddToCart Event with Request Context This example shows how to send an 'AddToCart' event and includes setting the request context, which is useful when integrating with web frameworks like Django. ```python import time from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.action_source import ActionSource from facebook_business.adobjects.serverside.event_request import EventRequest # In a Django view def add_to_cart_api(request): event = Event( event_name='AddToCart', event_time=int(time.time()), user_data=UserData(email='customer@example.com'), custom_data=CustomData(value=45.99, currency='USD'), action_source=ActionSource.WEBSITE ).set_request_context(request) request_obj = EventRequest(pixel_id='YOUR_PIXEL_ID', events=[event]) response = request_obj.execute() return JsonResponse({'status': 'success'}) ``` ``` -------------------------------- ### Complete E-commerce Purchase Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md This example shows how to create a UserData object, a CustomData object with various properties including items, and then construct and send a Purchase event using the Facebook SDK. ```APIDOC ## Complete E-commerce Example ### Description This example demonstrates how to send a 'Purchase' event to the Facebook Conversions API using the Python SDK. It includes detailed user data and custom data, such as order information, content details, and custom properties. ### Method POST (Implicitly via EventRequest.execute() which sends data to the Conversions API) ### Endpoint Not explicitly defined in the code, but the `EventRequest.execute()` method targets the Facebook Conversions API endpoint. ### Parameters #### Request Body (Constructed via SDK objects) - **pixel_id** (string) - Required - Your Facebook Pixel ID. - **events** (array of Event objects) - Required - A list containing one or more event objects. - **event_name** (string) - Required - The name of the event (e.g., 'Purchase'). - **event_time** (integer) - Required - Unix timestamp of when the event occurred. - **event_id** (string) - Required - A unique identifier for the event. - **user_data** (object) - Required - Contains information about the user. - **email** (string) - Optional - User's email address. - **phone** (string) - Optional - User's phone number. - **first_name** (string) - Optional - User's first name. - **last_name** (string) - Optional - User's last name. - **city** (string) - Optional - User's city. - **state** (string) - Optional - User's state. - **country_code** (string) - Optional - User's country code. - **zip_code** (string) - Optional - User's zip code. - **custom_data** (object) - Optional - Contains additional event-specific data. - **value** (float) - Optional - The total value of the purchase. - **currency** (string) - Optional - The currency of the purchase (e.g., 'USD'). - **content_name** (string) - Optional - The name of the content purchased. - **content_category** (string) - Optional - The category of the content. - **content_ids** (array of strings) - Optional - IDs of the content purchased. - **content_type** (string) - Optional - The type of content (e.g., 'product', 'product_group'). - **num_items** (integer) - Optional - The number of items purchased. - **order_id** (string) - Optional - The order ID. - **delivery_category** (string) - Optional - The delivery category (e.g., 'standard_shipping'). - **custom_properties** (object) - Optional - A key-value map for custom properties. - **event_source_url** (string) - Optional - The URL associated with the event. - **action_source** (string) - Required - The source of the action (e.g., 'WEBSITE'). ### Request Example ```python import time from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.action_source import ActionSource from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.api import FacebookAdsApi FacebookAdsApi.init(access_token='YOUR_ACCESS_TOKEN') # Customer information user_data = UserData( email='customer@example.com', phone='14155551234', first_name='Jane', last_name='Smith', city='San Francisco', state='CA', country_code='US', zip_code='94102' ) # Purchase details with multiple items custom_data = CustomData( value=249.98, currency='USD', content_name='Electronics Bundle', content_category='Electronics > Accessories', content_ids=['SKU-001', 'SKU-002'], content_type='product_group', num_items=2, order_id='ORD-2024-001-12345', delivery_category='standard_shipping', custom_properties={ 'shipping_cost': 10.00, 'tax': 20.00, 'discount_code': 'SUMMER20', 'discount_amount': 20.00, 'gift_wrap': True, 'is_returning_customer': True, 'customer_lifetime_value': 850.00 } ) # Create and send event event = Event( event_name='Purchase', event_time=int(time.time()), event_id='purchase_' + str(int(time.time() * 1000)), user_data=user_data, custom_data=custom_data, event_source_url='https://example.com/checkout/confirmation', action_source=ActionSource.WEBSITE ) request = EventRequest(pixel_id='YOUR_PIXEL_ID', events=[event]) response = request.execute() print(response) ``` ### Response #### Success Response (200) - **code** (string) - Indicates the status of the event processing (e.g., 'success'). - **message** (string) - A message describing the result of the event processing. - **pixel_rule_execution_results** (array) - Details about any rules that were executed for the pixel. #### Response Example ```json { "code": "success", "message": "Event received successfully.", "pixel_rule_execution_results": [] } ``` ``` -------------------------------- ### Send a Single Purchase Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event-request.md This example demonstrates how to construct and send a single 'Purchase' event to the Conversions API. Ensure FacebookAdsApi is initialized with your access token. ```python import time from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.action_source import ActionSource from facebook_business.api import FacebookAdsApi FacebookAdsApi.init(access_token='YOUR_ACCESS_TOKEN') user_data = UserData(email='customer@example.com') custom_data = CustomData(value=149.99, currency='USD') event = Event( event_name='Purchase', event_time=int(time.time()), event_id='order_001', user_data=user_data, custom_data=custom_data, action_source=ActionSource.WEBSITE, event_source_url='https://example.com/checkout/confirmation' ) request = EventRequest(pixel_id='123456789', events=[event]) response = request.execute() if 'events_received' in response: print(f"Successfully sent {response['events_received']} event(s)") ``` -------------------------------- ### Lead Event with Custom Properties Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Example of a Lead event including custom properties to capture specific lead details like score, source, and subscription tier. ```APIDOC ## Lead Event with Custom Properties ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( content_name='Premium Subscription Lead', content_type='subscription', status='pending_approval', custom_properties={ 'lead_score': 85, 'source': 'organic_search', 'subscription_tier': 'premium', 'contract_length_months': 12 } ) event = Event( event_name='Lead', event_time=1234567890, custom_data=custom_data ) ``` ``` -------------------------------- ### Common Campaign Methods Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/ad-objects-reference.md Provides examples for common operations performed on Campaign objects, including getting, updating, deleting, and retrieving related objects. ```APIDOC ## Common Campaign Methods ### Description Demonstrates how to perform common operations on Campaign objects using the Facebook Business SDK. ### Methods #### Get Campaign Data Retrieves specific fields of a campaign. ```python campaign = Campaign('123456789') campaign.api_get(fields=['name', 'status', 'daily_budget', 'objective']) ``` #### Update Campaign Updates existing fields of a campaign. ```python campaign.api_update(params={ Campaign.Field.name: 'Updated Name', Campaign.Field.daily_budget: 50000 # $500 }) ``` #### Pause Campaign Sets the campaign status to paused. ```python campaign.api_update(params={ Campaign.Field.status: Campaign.Status.paused }) ``` #### Delete Campaign Deletes a campaign. ```python campaign.api_delete() ``` #### Get Ad Sets in Campaign Retrieves all ad sets associated with a campaign. ```python adsets = campaign.get_adsets(fields=['id', 'name']) ``` #### Get Ads in Campaign Retrieves all ads within a campaign. ```python ads = campaign.get_ads() ``` #### Get Campaign Insights Retrieves performance insights for a campaign. ```python insights = campaign.get_insights( fields=['spend', 'impressions', 'actions'], params={'date_preset': 'last_7_days'} ) ``` ``` -------------------------------- ### Single Event Example Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event-request.md Demonstrates how to create and send a single event to the Facebook Server-Side API. This includes setting up user data, custom data, and event details. ```APIDOC ## Single Event ```python import time from facebook_business.adobjects.serverside.event import Event from facebook_business.adobjects.serverside.event_request import EventRequest from facebook_business.adobjects.serverside.user_data import UserData from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.action_source import ActionSource from facebook_business.api import FacebookAdsApi FacebookAdsApi.init(access_token='YOUR_ACCESS_TOKEN') user_data = UserData(email='customer@example.com') custom_data = CustomData(value=149.99, currency='USD') event = Event( event_name='Purchase', event_time=int(time.time()), event_id='order_001', user_data=user_data, custom_data=custom_data, action_source=ActionSource.WEBSITE, event_source_url='https://example.com/checkout/confirmation' ) request = EventRequest(pixel_id='123456789', events=[event]) response = request.execute() if 'events_received' in response: print(f"Successfully sent {response['events_received']} event(s)") ``` ``` -------------------------------- ### Set Action Source Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md Demonstrates setting the event source platform. ```python from facebook_business.adobjects.serverside.action_source import ActionSource event = Event(event_name='Purchase', event_time=1234567890, action_source=ActionSource.WEBSITE) ``` -------------------------------- ### FacebookSession Initialization with Proxies and Timeout Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-session.md Illustrates creating multiple FacebookSession instances for different users, configuring them with proxy settings and custom timeouts for network requests. ```python from facebook_business.session import FacebookSession from facebook_business.api import FacebookAdsApi proxies = { 'http': 'http://proxy.example.com:8080', 'https': 'https://proxy.example.com:8443' } # Create sessions for different users session1 = FacebookSession( app_id='YOUR_APP_ID', app_secret='YOUR_APP_SECRET', access_token='USER_1_ACCESS_TOKEN', proxies=proxies, timeout=30 ) session2 = FacebookSession( app_id='YOUR_APP_ID', app_secret='YOUR_APP_SECRET', access_token='USER_2_ACCESS_TOKEN', proxies=proxies, timeout=30 ) # Create separate API instances for each session api1 = FacebookAdsApi(session1) api2 = FacebookAdsApi(session2) ``` -------------------------------- ### Create a Product Purchase Event with Details Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Illustrates creating a Purchase event with detailed product information, such as content name, category, IDs, type, quantity, and order ID. This provides richer context for purchases. ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( value=299.99, currency='USD', content_name='Sony WH-1000XM4 Headphones', content_category='Electronics > Audio', content_ids=['SKU-12345', 'GTIN-567890123456'], content_type='product', num_items=1, order_id='ORDER-20240101-001' ) event = Event( event_name='Purchase', event_time=1234567890, custom_data=custom_data ) ``` -------------------------------- ### Complete CRUD Workflow for Campaigns Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Shows how to initialize the API, create, read, update, retrieve related adsets, and delete a campaign. Ensure you replace placeholder values with your actual credentials and account ID. ```python from facebook_business.adobjects.adaccount import AdAccount from facebook_business.adobjects.campaign import Campaign from facebook_business.api import FacebookAdsApi # Initialize API api = FacebookAdsApi.init( app_id='YOUR_APP_ID', app_secret='YOUR_APP_SECRET', access_token='YOUR_ACCESS_TOKEN', account_id='act_123456789' ) account = AdAccount('act_123456789') # CREATE new_campaign = account.create_campaign( fields=[], params={ Campaign.Field.name: 'Test Campaign', Campaign.Field.objective: Campaign.Objective.conversions, Campaign.Field.status: Campaign.Status.paused, Campaign.Field.daily_budget: 10000 # $100 in cents } ) campaign_id = new_campaign.get(Campaign.Field.id) print(f"Created: {campaign_id}") # READ campaign = Campaign(campaign_id) campaign.api_get(fields=[ Campaign.Field.name, Campaign.Field.status, Campaign.Field.daily_budget ]) print(f"Name: {campaign[Campaign.Field.name]}") # UPDATE campaign.api_update(params={ Campaign.Field.name: 'Renamed Campaign', Campaign.Field.daily_budget: 20000 # Increase to $200 }) print("Updated") # GET RELATED (Read edges) adsets = campaign.get_adsets() for adset in adsets: print(f"Ad Set: {adset.get('name')}") # DELETE campaign.api_delete() print("Deleted") ``` -------------------------------- ### Create a ViewContent Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Demonstrates how to create a ViewContent event with product details, including name, category, IDs, type, value, and currency. This is useful for tracking user engagement with specific products or content. ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( content_name='iPhone 15 Pro', content_category='Electronics > Mobile Phones', content_ids=['IPHONE-15-PRO-128GB'], content_type='product', value=999.99, currency='USD' ) event = Event( event_name='ViewContent', event_time=1234567890, custom_data=custom_data ) ``` -------------------------------- ### Create a Simple Purchase Event Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Shows how to create a basic Purchase event with essential custom data, including value and currency. This is useful for tracking simple transactions. ```python from facebook_business.adobjects.serverside.custom_data import CustomData from facebook_business.adobjects.serverside.event import Event custom_data = CustomData( value=149.99, currency='USD' ) event = Event( event_name='Purchase', event_time=1234567890, custom_data=custom_data ) ``` -------------------------------- ### Initialize and Set CustomData Properties Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-custom-data.md Demonstrates how to initialize a CustomData object and set its properties, including value, currency, and number of items. Accessing properties via getters is also shown. ```python from facebook_business.adobjects.serverside.custom_data import CustomData data = CustomData(value=99.99, currency='USD') print(data.value) # 99.99 print(data.currency) # 'USD' data.num_items = 3 print(data.num_items) # 3 ``` -------------------------------- ### Set Custom Data Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md Example of setting custom conversion data for an event. ```python from facebook_business.adobjects.serverside.custom_data import CustomData custom_data = CustomData(value=99.99, currency='USD', content_name='Product A') event = Event(event_name='Purchase', event_time=1234567890, custom_data=custom_data) ``` -------------------------------- ### Event Properties Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md Details on the properties of the Event object, including how to get and set them. ```APIDOC ## Event Properties ### event_name Gets or sets the event name. Required field. ### event_time Gets or sets the Unix timestamp (seconds) when the event occurred. Required field. ### event_source_url Gets or sets the source URL where the event occurred. ### opt_out Gets or sets the opt-out flag for data sales. ### event_id Gets or sets a unique event identifier for deduplication. ### user_data Gets or sets user information. ### custom_data Gets or sets custom conversion data. ### action_source Gets or sets the event source platform. ### referrer_url Gets or sets the referrer URL. ``` -------------------------------- ### Run Unit Tests with Python Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/README.md Execute unit tests for the SDK using the default Python interpreter. No access token or network access is required. ```bash python -m facebook_business.test.unit ``` -------------------------------- ### Get Custom Audience Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/ad-objects-reference.md Retrieves details of an existing custom audience using its ID. ```APIDOC ## Get Custom Audience ### Description Retrieves details of an existing custom audience using its ID. ### Method GET ### Endpoint /act_ACCOUNT_ID/customaudiences/{audience_id} ### Parameters #### Path Parameters - **ACCOUNT_ID** (string) - Required - The ID of the ad account. - **audience_id** (string) - Required - The ID of the custom audience to retrieve. ### Response #### Success Response (200) - **id** (string) - The ID of the custom audience. - **name** (string) - The name of the custom audience. - **subtype** (string) - The subtype of the custom audience. - **customer_file_source** (string) - The source of the customer file. - **description** (string) - The description of the custom audience. #### Response Example ```json { "id": "1234567890123", "name": "My Customers", "subtype": "CUSTOM", "customer_file_source": "CRM", "description": "Customers from our database" } ``` ``` -------------------------------- ### Set Event ID for Deduplication Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-event.md Example of setting a unique event identifier for deduplication purposes. ```python event = Event(event_name='Purchase', event_time=1234567890, event_id='unique_event_id_123') ``` -------------------------------- ### Initialize Facebook Ads API with Environment Variables Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/configuration.md Initialize the FacebookAdsApi by reading credentials and debug settings from environment variables. Ensure these variables are set before running the code. ```python import os from facebook_business.api import FacebookAdsApi api = FacebookAdsApi.init( app_id=os.getenv('FB_APP_ID'), app_secret=os.getenv('FB_APP_SECRET'), access_token=os.getenv('FB_ACCESS_TOKEN'), account_id=os.getenv('FB_ACCOUNT_ID'), debug=os.getenv('DEBUG', '').lower() == 'true' ) ``` -------------------------------- ### __len__() - Get Batch Size Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api-batch.md Returns the number of API requests currently queued in the batch. ```APIDOC ## `__len__()` Return the number of requests currently queued in the batch. **Returns:** `int` — Number of pending requests **Example:** ```python batch = api.new_batch() batch.add('GET', ('me', 'adaccounts')) batch.add('GET', ('me', 'businesses')) print(f"Batch size: {len(batch)}") # Output: Batch size: 2 ``` ``` -------------------------------- ### UserData Object Initialization and Properties Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/conversions-api-user-data.md Demonstrates how to initialize a UserData object and access its properties using getter and setter methods. ```APIDOC ## UserData Object Initialization and Properties ### Description All constructor parameters for the UserData object have corresponding getter and setter properties. This allows for easy modification and retrieval of user data fields. ### Example ```python from facebook_business.adobjects.serverside.user_data import UserData # Initialize UserData with an email user = UserData(email='john@example.com') print(user.email) # Output: 'john@example.com' # Set a phone number using the setter property user.phone = '14155551234' print(user.phone) # Output: '14155551234' ``` ``` -------------------------------- ### Request Statistics Example Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api.md Demonstrates how to retrieve the number of attempted and succeeded API requests using the FacebookAdsApi. ```python from facebook_business.api import FacebookAdsApi api = FacebookAdsApi.get_default_api() # Make some API calls # ... attempts = api.get_num_requests_attempted() successes = api.get_num_requests_succeeded() print(f"Attempted: {attempts}, Succeeded: {successes}") ``` -------------------------------- ### Initialize FacebookAdsApi with Network Configuration Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/configuration.md Set up proxy servers and request timeouts for network communication. This is essential when operating in environments with network restrictions or when you need to control the duration of API requests. ```python proxies = { 'http': 'http://proxy.example.com:8080', 'https': 'https://proxy.example.com:8443' } api = FacebookAdsApi.init( access_token='YOUR_TOKEN', proxies=proxies, timeout=30 ) ``` -------------------------------- ### Basic FacebookSession Initialization Source: https://github.com/facebook/facebook-python-business-sdk/blob/main/_autodocs/api-reference/facebook-session.md Shows how to create a basic FacebookSession instance with essential credentials and set it as the default API for the FacebookAdsApi. ```python from facebook_business.session import FacebookSession from facebook_business.api import FacebookAdsApi # Create a session with minimal configuration session = FacebookSession( app_id='YOUR_APP_ID', app_secret='YOUR_APP_SECRET', access_token='YOUR_ACCESS_TOKEN' ) # Create an API instance using the session api = FacebookAdsApi(session) FacebookAdsApi.set_default_api(api) ```