### Complete Batch Example Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/api-request-response.md Demonstrates how to add multiple GET requests to a batch and execute them, processing individual responses. ```APIDOC ## Complete Batch Example This example shows how to create a batch of API requests, add multiple GET operations to it, and then execute the batch. It includes a callback function for each request to handle its specific response. ### Method Batch execution is asynchronous. Individual requests are added using `batch.add()`. ### Endpoint Not applicable directly; requests are defined by their paths within the `batch.add()` method. ### Parameters - `api`: An initialized `FacebookAdsApi` instance. - `method`: The HTTP method for the request (e.g., 'GET'). - `path`: The API path for the request (e.g., `['campaign_1']`). - `params`: Optional query parameters for the request. - `callback`: A function to process the response of each individual request. ### Request Example ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const api = adsSdk.FacebookAdsApi.init(''); const batch = new adsSdk.FacebookAdsApiBatch(api); // Add multiple requests batch.add( 'GET', ['campaign_1'], { fields: 'id,name,status' }, undefined, (response) => { if (response.isSuccess) { const campaign = response.getContent(); console.log('Campaign 1:', campaign.name); } else { const error = response.getError(); console.log('Error:', error.message); } } ); batch.add( 'GET', ['campaign_2'], { fields: 'id,name,status' }, undefined, (response) => { if (response.isSuccess) { const campaign = response.getContent(); console.log('Campaign 2:', campaign.name); } } ); // Execute batch await batch.execute(); ``` ### Response Responses are handled individually within the callback functions provided to `batch.add()`. ``` -------------------------------- ### Install, Initialize, Read Account, Get Campaigns, and Handle Errors Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/00_START_HERE.md This snippet demonstrates the essential steps for using the Facebook Business SDK: installing the package, initializing the API with an access token, reading an ad account's details, fetching campaigns associated with that account, and implementing basic error handling. ```javascript // 1. Install npm install facebook-nodejs-business-sdk // 2. Initialize const adsSdk = require('facebook-nodejs-business-sdk'); const api = adsSdk.FacebookAdsApi.init(''); // 3. Read an account const account = new adsSdk.AdAccount('act_'); await account.read([adsSdk.AdAccount.Fields.name, adsSdk.AdAccount.Fields.balance]); console.log(account.name, account.balance); // 4. Get campaigns const campaigns = await account.getCampaigns([adsSdk.Campaign.Fields.name]); campaigns.forEach(c => console.log(c.name)); // 5. Handle errors try { await account.read([...]); } catch (error) { console.log('Status:', error.status, 'Message:', error.message); } ``` -------------------------------- ### Complete Conversions API Example Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/conversions-api.md A comprehensive example demonstrating the initialization of the Facebook Ads API, creation of user and custom data, constructing a server event, and executing the event request. This snippet shows the full flow from setup to sending an event. ```javascript const bizSdk = require('facebook-nodejs-business-sdk'); bizSdk.FacebookAdsApi.init(''); const userData = (new bizSdk.UserData()) .setEmail('joe@eg.com') .setClientIpAddress(request.connection.remoteAddress) .setClientUserAgent(request.headers['user-agent']); const customData = (new bizSdk.CustomData()) .setCurrency('USD') .setValue(123.45); const serverEvent = (new bizSdk.ServerEvent()) .setEventName('Purchase') .setEventTime(Math.floor(Date.now() / 1000)) .setUserData(userData) .setCustomData(customData) .setEventSourceUrl('http://example.com/checkout') .setActionSource('website'); const response = await (new bizSdk.EventRequest('', '')) .setEvents([serverEvent]) .execute(); console.log('Response:', response); ``` -------------------------------- ### Complete Batch Example Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/api-request-response.md This snippet shows how to add multiple GET requests to a batch and execute them. It includes basic success and error logging for each request. ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const api = adsSdk.FacebookAdsApi.init(''); const batch = new adsSdk.FacebookAdsApiBatch(api); // Add multiple requests batch.add( 'GET', ['campaign_1'], { fields: 'id,name,status' }, undefined, (response) => { if (response.isSuccess) { const campaign = response.getContent(); console.log('Campaign 1:', campaign.name); } else { const error = response.getError(); console.log('Error:', error.message); } } ); batch.add( 'GET', ['campaign_2'], { fields: 'id,name,status' }, undefined, (response) => { if (response.isSuccess) { const campaign = response.getContent(); console.log('Campaign 2:', campaign.name); } } ); // Execute batch await batch.execute(); ``` -------------------------------- ### Install Dependencies Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md Installs project dependencies using npm and bower. Ensure Gulp and Bower are installed globally. ```bash npm install bower install ``` -------------------------------- ### Get Campaign Performance Insights Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md This example demonstrates how to retrieve performance insights for a campaign using the `getInsights` method. It specifies the desired fields and a date range, then iterates through the results to log key metrics. ```APIDOC ## Get Campaign Performance Insights This example demonstrates how to retrieve performance insights for a campaign using the `getInsights` method. It specifies the desired fields and a date range, then iterates through the results to log key metrics. ### Method ```javascript await campaign.getInsights(fields, options) ``` ### Parameters #### Path Parameters None #### Query Parameters - **fields** (Array) - Required - A list of AdsInsights fields to retrieve. - **options** (Object) - Optional - An object containing query parameters such as `date_start`, `date_stop`, and `level`. - **date_start** (string) - The start date for the insights data. - **date_stop** (string) - The end date for the insights data. - **level** (string) - The level at which to retrieve insights (e.g., 'campaign', 'adset', 'ad'). ### Request Example ```javascript // Get campaign performance const insights = await campaign.getInsights( [ adsSdk.AdsInsights.Fields.spend, adsSdk.AdsInsights.Fields.impressions, adsSdk.AdsInsights.Fields.clicks, adsSdk.AdsInsights.Fields.cpc, adsSdk.AdsInsights.Fields.actions ], { date_start: '2024-01-01', date_stop: '2024-12-31', level: 'campaign' // Get campaign-level data } ); let totalSpend = 0; insights.forEach(row => { console.log(`Date: ${row.date_start}`); console.log(` Spend: ${row.spend}`); console.log(` Impressions: ${row.impressions}`); console.log(` CPC: ${row.cpc}`); totalSpend += parseFloat(row.spend); }); console.log(`Total spend: ${totalSpend}`); ``` ### Response #### Success Response An array of AdsInsights objects, each containing the requested fields for the specified period and level. ``` -------------------------------- ### Using APIRequest with Batch Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/api-request-response.md This example demonstrates how to create individual APIRequest objects and add them to a batch. It allows for more granular configuration of each request before batch execution. ```javascript const request1 = new adsSdk.APIRequest(api, 'GET', ['campaign_1']); request1.setFields(['id', 'name']) .setParams({ limit: 10 }); const request2 = new adsSdk.APIRequest(api, 'GET', ['campaign_2']); request2.setFields(['id', 'name']); const batch = new adsSdk.FacebookAdsApiBatch(api); batch.addRequest(request1, (response) => { console.log('Campaign 1:', response.getContent()); }); batch.addRequest(request2, (response) => { console.log('Campaign 2:', response.getContent()); }); await batch.execute(); ``` -------------------------------- ### Get and Create Ads Pixels Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Illustrates how to retrieve a list of existing pixels with their IDs and names, and then how to create a new pixel with a specified name. ```javascript // Get pixels const pixels = await account.getPixels( [adsSdk.AdsPixel.Fields.id, adsSdk.AdsPixel.Fields.name] ); pixels.forEach(pixel => { console.log(`Pixel ${pixel.id}: ${pixel.name}`); }); // Create pixel const newPixel = await account.createPixel( [adsSdk.AdsPixel.Fields.id], { [adsSdk.AdsPixel.Fields.name]: 'My Pixel' } ); console.log('Created pixel:', newPixel.id); ``` -------------------------------- ### AdSet Targeting Example Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Defines a targeting configuration for an AdSet, including geo-locations, age, gender, interests, and behaviors. ```javascript const targeting = { geo_locations: { countries: ['US', 'CA'] }, age_min: 18, age_max: 65, genders: [1, 2], // 1=Female, 2=Male user_adclusters: [123, 456], // Interest codes behaviors: [{ id: 'behavior_id' }] }; adSet.targeting = JSON.stringify(targeting); ``` -------------------------------- ### AdAccount Class Usage Example Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/ad-account.md Demonstrates how to instantiate an AdAccount, read specific fields, modify a property, and update the account via the API. Only changed properties are sent in the update call. ```APIDOC ## AdAccount Class Usage ### Description This example shows how to interact with the `AdAccount` class to fetch data, modify properties, and send updates to the Facebook API. The SDK intelligently tracks changes to properties, ensuring only modified fields are included in the `update()` call. ### Method ```javascript new AdAccount('act_123') .read([AdAccount.Fields.spend_cap, AdAccount.Fields.name]) .spend_cap = 100000; account.update(); ``` ### Parameters - **AdAccount constructor**: Takes the Ad Account ID as a string (e.g., 'act_123'). - **read()**: Accepts an array of `AdAccount.Fields` to specify which fields to retrieve. - **spend_cap property assignment**: Sets the value for the `spend_cap` property. This change is tracked. - **update()**: Sends only the tracked changed properties to the API. ### Request Example ```javascript // Instantiating and setting a property const account = new AdAccount('act_123'); account.spend_cap = 100000; // Calling update will send only the changed 'spend_cap' field account.update(); ``` ### Response - **update()**: The `update()` method does not return a specific value in this context, but it triggers an API call to update the ad account. ### Notes - The `AdAccount.Fields` enum provides a list of available fields that can be read or updated. - Property assignments like `account.spend_cap = 100000` directly modify the object and mark the field for update. ``` -------------------------------- ### Implement Custom HTTP Service for Requests Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/configuration.md Provide a custom HTTP service to handle requests with special requirements like proxies or custom headers. The example demonstrates adding a custom header to fetch requests. ```javascript class CustomHttpService { sendRequest(url, method, body, headers) { // Custom implementation return fetch(url, { method, body, headers: { ...headers, 'X-Custom-Header': 'value' } }).then(r => ({ statusCode: r.status, body: r.text() })); } } const eventRequest = new EventRequest( '', '', [], null, null, null, null, null, null, false, new CustomHttpService() ); ``` -------------------------------- ### Add GET Request to Batch Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/batch-api.md Add a GET request to the batch with specific fields and callbacks for success and failure. ```javascript const batch = new FacebookAdsApiBatch(api); // Add a GET request batch.add( 'GET', ['act_'], { fields: 'id,name,balance' }, undefined, (response) => { console.log('Account:', response.getContent()); }, (response) => { console.log('Error:', response.getError()); } ); ``` -------------------------------- ### Get Edge with Immediate Fetch Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Initializes a Cursor to paginate through edge/relationship objects and immediately fetches the first page. Useful for retrieving related objects with specific fields and parameters. ```javascript const campaigns = await account.getEdge( Campaign, [Campaign.Fields.name, Campaign.Fields.status], { limit: 10 }, true, 'campaigns' ); ``` -------------------------------- ### Get Campaigns with Pagination Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/README.md Retrieves a list of campaigns with specified fields and a limit. Supports pagination to fetch subsequent pages of results. ```javascript const campaigns = await account.getCampaigns( [adsSdk.Campaign.Fields.id, adsSdk.Campaign.Fields.name, adsSdk.Campaign.Fields.status], { limit: 10 } ); campaigns.forEach(campaign => { console.log(`${campaign.name} (${campaign.status})`); }); // Paginate through results if (campaigns.hasNext()) { const nextPage = await campaigns.next(); // Process next page... } ``` -------------------------------- ### Conversions API with Parameter Builder Integration Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md This example shows how to integrate the Conversions API Parameter Builder to auto-fill event parameters directly from an incoming HTTP request. The `setRequestContext()` method is used, and an optional `Preference` object can gate which fields are auto-filled. ```javascript const Preference = bizSdk.Preference; const serverEvent = (new ServerEvent()) .setEventName('Purchase') .setEventTime(Math.floor(Date.now() / 1000)) .setUserData((new UserData()).setEmail('joe@eg.com')) .setActionSource('website') .setRequestContext(request); // Optional: gate which fields may be auto-filled (all default true). // Order: fbc, fbp, client_ip_address, referrer_url, event_source_url. // .setRequestContext(request, new Preference(true, true, true, true, false)); ``` -------------------------------- ### Create and Get Custom Audiences Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Demonstrates creating a new custom audience from CRM data and then retrieving a list of existing custom audiences with their names and approximate counts. ```javascript // Create custom audience const newAudience = await account.createCustomAudience( [CustomAudience.Fields.id], { [CustomAudience.Fields.name]: 'My CRM Audience', [CustomAudience.Fields.customer_file_source]: 'USER_PROVIDED_ONLY' }, CustomAudience ); console.log('Created audience:', newAudience.id); // Get audiences const audiences = await account.getCustomAudiences( [CustomAudience.Fields.id, CustomAudience.Fields.name, CustomAudience.Fields.approximate_count] ); audiences.forEach(aud => { console.log(`${aud.name}: ~${aud.approximate_count} people`); }); ``` -------------------------------- ### Configure Preference for setRequestContext Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/configuration.md Instantiate a Preference object to control which fields are automatically populated when using setRequestContext. This example disables auto-filling the referrer URL. ```javascript const pref = new Preference(true, true, true, true, false); // Disable referrer_url auto-fill const event = new ServerEvent() .setRequestContext(request, pref); ``` -------------------------------- ### Batch Request Error Handling and Retries Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/errors.md Explains that individual request failures within a batch are not thrown as exceptions. This example shows a pattern for executing a batch and retrying the entire batch if it returns partial failures. ```javascript let retryBatch = new FacebookAdsApiBatch(api); let retryCount = 0; const resultBatch = await retryBatch.execute(); if (resultBatch) { console.log('Some requests failed, retrying...'); if (retryCount < 3) { retryCount++; resultBatch = await resultBatch.execute(); } } ``` -------------------------------- ### Batch API Response Structure and Callbacks Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/batch-api.md Illustrates how to access success and failure information from an APIResponse object within batch request callbacks. Shows how to check `isSuccess`, get content, and retrieve error details. ```javascript batch.add( 'GET', [campaignId], { fields: 'name' }, undefined, (response) => { // Success case const isSuccess = response.isSuccess; const content = response.getContent(); console.log(isSuccess, content); }, (response) => { // Failure case const error = response.getError(); const code = response.getErrorCode(); console.log('Error:', code, error); } ); ``` -------------------------------- ### Batch Operations with Cursor Data Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/cursor.md Utilize batch API calls for bulk operations on items retrieved via a cursor. This example demonstrates adding GET requests for campaign names to a batch. ```javascript const batch = new FacebookAdsApiBatch(api); let page = await account.getCampaigns([Campaign.Fields.id]); page.forEach(campaign => { batch.add('GET', [campaign.id], { fields: Campaign.Fields.name }); }); while (page.hasNext()) { page = await page.next(); page.forEach(campaign => { batch.add('GET', [campaign.id], { fields: Campaign.Fields.name }); }); } await batch.execute(); ``` -------------------------------- ### Accessing and Creating Campaign Fields Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md Demonstrates how to initialize the SDK, access ad account properties, and create a campaign with specified fields and objective. Fields are accessed as properties of node objects. ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const accessToken = ''; const api = adsSdk.FacebookAdsApi.init(accessToken); const AdAccount = adsSdk.AdAccount; const Campaign = adsSdk.Campaign; const account = new AdAccount('act_'); console.log(account.id) // fields can be accessed as properties account .createCampaign( [Campaign.Fields.Id], { [Campaign.Fields.name]: 'Page likes campaign', // Each object contains a fields map with a list of fields supported on that object. [Campaign.Fields.status]: Campaign.Status.paused, [Campaign.Fields.objective]: Campaign.Objective.page_likes } ) .then((result) => { }) .catch((error) => { }); ``` -------------------------------- ### Iterating All Campaigns with Async/Await Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md Demonstrates an efficient way to iterate through all campaigns under an Ad Account using `async/await` and the `Cursor`'s `hasNext` and `next` methods. This is a recommended practice for handling large datasets. ```javascript const adsSdk = require('facebook-nodejs-ads-sdk'); const accessToken = ''; const api = adsSdk.FacebookAdsApi.init(accessToken); const AdAccount = adsSdk.AdAccount; const account = new AdAccount('act_'); void async function () { let campaigns = await account.getCampaigns([Campaign.Fields.name], {limit: 20}); campaigns.forEach(c => console.log(c.name)); while (campaigns.hasNext()) { campaigns = await campaigns.next(); campaigns.forEach(c => console.log(c.name)); } }(); ``` -------------------------------- ### Initialize FacebookAdsApi with Constructor Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/configuration.md Instantiate the FacebookAdsApi with an access token, locale, and crash log setting. ```javascript const api = new FacebookAdsApi('', 'en_US', true); ``` -------------------------------- ### Facebook SDK Error Response Body Example Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/errors.md An example of the error structure found within the 'response' property of a FacebookRequestError. ```javascript error.response = { error: { code: 100, message: 'Invalid parameter', type: 'OAuthException', fbtrace_id: '...' } } ``` -------------------------------- ### Get Ad Account ID Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/ad-account.md Retrieve the unique identifier for the ad account. ```javascript account.getId(); ``` -------------------------------- ### Async/Await for All Campaigns Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/cursor.md Fetch all campaigns from an account efficiently using async/await and a while loop. Recommended for large datasets to collect all items into an array. ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); async function getAllCampaigns(account) { const campaigns = []; let page = await account.getCampaigns( [adsSdk.Campaign.Fields.id, adsSdk.Campaign.Fields.name], { limit: 25 } ); // Add campaigns from first page campaigns.push(...page); // Continue fetching while more pages exist while (page.hasNext()) { page = await page.next(); campaigns.push(...page); } return campaigns; } // Usage const account = new adsSdk.AdAccount('act_'); const allCampaigns = await getAllCampaigns(account); console.log(`Total campaigns: ${allCampaigns.length}`); ``` -------------------------------- ### Get Object ID Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Use getId to retrieve the unique identifier for the object. An error is thrown if the ID has not been set. ```javascript getId(): string ``` ```javascript const campaign = new Campaign(''); const id = campaign.getId(); // Returns '' ``` -------------------------------- ### Initialize BatchProcessor Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/configuration.md Instantiate BatchProcessor with batch size and concurrent request limits. Recommended batch size is 50 for maximum throughput, and 5-10 concurrent requests for a balance between throughput and rate limiting. ```javascript new BatchProcessor(batch_size, concurrent_requests) ``` ```javascript const processor = new BatchProcessor( 50, // Send 50 events per request 5 // Keep 5 requests in flight simultaneously ); await processor.processEvents(baseRequest, allEvents); ``` -------------------------------- ### Get Ads Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/ad-account.md Retrieve ads associated with an ad account. Supports fetching specific fields and applying query parameters. ```javascript account.getAds([adsSdk.Ad.Fields.id, adsSdk.Ad.Fields.name]) .then(ads => { ads.forEach(ad => console.log(ad.name)); }); ``` -------------------------------- ### Using APIRequest with Batch Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/api-request-response.md Shows how to create individual `APIRequest` objects and add them to a batch for execution. ```APIDOC ## Using APIRequest with Batch This example demonstrates creating `APIRequest` objects separately and then adding them to a `FacebookAdsApiBatch` for execution. This approach allows for more granular control over individual requests before batching. ### Method Requests are created using `adsSdk.APIRequest` and added to the batch using `batch.addRequest()`. ### Endpoint Requests are defined by their paths when creating `APIRequest` objects. ### Parameters - `api`: An initialized `FacebookAdsApi` instance. - `request`: An `APIRequest` object configured with method, path, fields, and parameters. - `callback`: A function to process the response of the added request. ### Request Example ```javascript const request1 = new adsSdk.APIRequest(api, 'GET', ['campaign_1']); request1.setFields(['id', 'name']) .setParams({ limit: 10 }); const request2 = new adsSdk.APIRequest(api, 'GET', ['campaign_2']); request2.setFields(['id', 'name']); const batch = new adsSdk.FacebookAdsApiBatch(api); batch.addRequest(request1, (response) => { console.log('Campaign 1:', response.getContent()); }); batch.addRequest(request2, (response) => { console.log('Campaign 2:', response.getContent()); }); await batch.execute(); ``` ### Response Responses are processed by the callback functions provided to `batch.addRequest()`. ``` -------------------------------- ### FacebookAdsApi Initialization and Basic Usage Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/README.md Demonstrates how to initialize the FacebookAdsApi with an access token, enable debugging, and retrieve the default API instance. This is the primary entry point for interacting with the Facebook Graph API via the SDK. ```APIDOC ## FacebookAdsApi ### Description The main API client for all Graph API operations. Used for initializing the SDK and making requests. ### Methods - **`init(accessToken: string, options?: object)`**: Initialize default API instance. - **`call(path: string, method: string, params?: object, config?: object)`**: Execute HTTP requests. - **`setDebug(debug: boolean)`**: Enable or disable request logging. - **`getDefaultApi(): FacebookAdsApi`**: Get the default API instance. ### Request Example (Initialization) ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const api = adsSdk.FacebookAdsApi.init(''); api.setDebug(true); // Optional: enable logging const defaultApi = adsSdk.FacebookAdsApi.getDefaultApi(); ``` ### Response - **Success Response**: The `init` method returns the initialized `FacebookAdsApi` instance. `getDefaultApi` returns the singleton `FacebookAdsApi` instance. `setDebug` returns void. ### Error Handling - `init` may throw errors if the access token is invalid or missing. - `call` will propagate `FacebookRequestError` for API-level issues. ``` -------------------------------- ### AppData Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/types.md App-specific data for mobile app events, including tracking enablement, installer information, and deep link URL schemes. ```APIDOC ## AppData ### Description App-specific data for mobile app events, including tracking enablement, installer information, and deep link URL schemes. ### Properties - **advertiser_tracking_enabled** (boolean) - App tracking enabled - **application_tracking_enabled** (boolean) - Legacy ATT flag - **extinfo** (string[]) - Extended info parameters - **installer_package** (string) - App installer package - **install_referrer** (string) - Google Play install referrer - **install_referrer_source** (string) - Install referrer source - **url_schemes** (string[]) - Deep link URL schemes ### Used by ServerEvent.setAppData() ``` -------------------------------- ### Get Custom Audiences Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/ad-account.md Retrieve custom audiences associated with an ad account. Specify fields to fetch and optional query parameters. ```javascript account.getCustomAudiences([adsSdk.CustomAudience.Fields.id, adsSdk.CustomAudience.Fields.name]) .then(audiences => { audiences.forEach(aud => console.log(aud.name)); }); ``` -------------------------------- ### Initialize FacebookAdsApi with init() Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/configuration.md Initialize the FacebookAdsApi and set it as the default API instance for global access. Requires an access token. ```javascript const api = FacebookAdsApi.init(''); // Now available globally via FacebookAdsApi.getDefaultApi() ``` -------------------------------- ### Get Ad Sets Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/ad-account.md Retrieve ad sets under an ad account. You can specify fields to fetch and use query parameters for filtering. ```javascript account.getAdSets([adsSdk.AdSet.Fields.id, adsSdk.AdSet.Fields.name], { limit: 5 }) .then(adSets => { adSets.forEach(adSet => console.log(adSet.name)); }); ``` -------------------------------- ### FacebookAdsApi.init Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api.md Instantiates an API instance and sets it as the default for all subsequent operations. This is a convenient way to initialize the SDK with a single access token. ```APIDOC ## Static Method FacebookAdsApi.init ### Description Instantiate an API instance and store it as the default for all subsequent operations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | accessToken | string | Yes | — | Valid access token for Graph API authentication | | locale | string | No | 'en_US' | Locale for API responses | | crash_log | boolean | No | true | Enable crash reporting | ### Returns FacebookAdsApi instance ### Example ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const api = adsSdk.FacebookAdsApi.init(''); ``` ``` -------------------------------- ### Manage Campaign with Facebook SDK Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Initializes the SDK, reads campaign details, updates the campaign name and daily budget, and retrieves associated ad sets. ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); adsSdk.FacebookAdsApi.init(''); const campaign = new adsSdk.Campaign(''); await campaign.read([adsSdk.Campaign.Fields.name, adsSdk.Campaign.Fields.status]); console.log(campaign.name, campaign.status); campaign.name = 'Updated Campaign Name'; campaign.daily_budget = 100000; // In currency await campaign.update(); // Get ad sets const adSets = await campaign.getAdSets([adsSdk.AdSet.Fields.id, adsSdk.AdSet.Fields.name]); adSets.forEach(adSet => console.log(adSet.name)); ``` -------------------------------- ### Get API Instance Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Use getApi to access the FacebookAdsApi instance associated with the object. This allows for further API configurations, such as enabling debugging. ```javascript getApi(): FacebookAdsApi ``` ```javascript const campaign = new Campaign(''); const api = campaign.getApi(); api.setDebug(true); ``` -------------------------------- ### Creating a Campaign Object Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md Illustrates the process of creating a new campaign with specific parameters, including name, status, and objective. An empty array is passed for fields when not explicitly needed during creation. ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const accessToken = ''; const api = adsSdk.FacebookAdsApi.init(accessToken); const AdAccount = adsSdk.AdAccount; const Campaign = adsSdk.Campaign; const account = new AdAccount('act_'); account .createCampaign( [], { [Campaign.Fields.name]: 'Page likes campaign', [Campaign.Fields.status]: Campaign.Status.paused, [Campaign.Fields.objective]: Campaign.Objective.page_likes } ) .then((campaign) => { }) .catch((error) => { }); ``` -------------------------------- ### Get SDK Version Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api.md Retrieve the version of the Facebook Business SDK for Node.js. This is a static getter that returns a string representing the SDK version. ```javascript const sdkVersion = FacebookAdsApi.SDK_VERSION; ``` -------------------------------- ### Async/Await with While Loop (Recommended for Large Datasets) Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/cursor.md Provides a recommended approach for handling large datasets by fetching all results into an array using async/await and a while loop. ```APIDOC ## Async/Await with While Loop (Recommended for Large Datasets) This method is recommended for fetching large datasets. It efficiently retrieves all items by accumulating them into an array using asynchronous operations and a `while` loop. ### Method `account.getCampaigns(fields, options)` - Fetches campaigns with specified fields and options. `page.hasNext()` - Returns `true` if there are more pages of results. `page.next()` - Fetches the next page of results. ### Example ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); async function getAllCampaigns(account) { const campaigns = []; let page = await account.getCampaigns( [adsSdk.Campaign.Fields.id, adsSdk.Campaign.Fields.name], { limit: 25 } ); campaigns.push(...page); while (page.hasNext()) { page = await page.next(); campaigns.push(...page); } return campaigns; } // Usage const account = new adsSdk.AdAccount('act_'); const allCampaigns = await getAllCampaigns(account); console.log(`Total campaigns: ${allCampaigns.length}`); ``` ``` -------------------------------- ### Get Campaigns Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/ad-account.md Retrieve campaigns associated with an ad account. Supports fetching specific fields and applying query parameters for filtering and pagination. ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); adsSdk.FacebookAdsApi.init(''); const account = new adsSdk.AdAccount('act_'); account.getCampaigns([adsSdk.Campaign.Fields.id, adsSdk.Campaign.Fields.name], { limit: 10 }) .then(campaigns => { campaigns.forEach(campaign => { console.log('Campaign:', campaign.name); }); if (campaigns.hasNext()) { return campaigns.next(); } }) .catch(error => console.error(error)); ``` -------------------------------- ### Navigating Campaign Pages with Cursors Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/README.md Illustrates using the `Cursor` class to fetch paginated campaign data. It shows how to retrieve the next and previous pages of results, with checks for `hasNext` and `hasPrevious`. ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const accessToken = ''; const api = adsSdk.FacebookAdsApi.init(accessToken); const AdAccount = adsSdk.AdAccount; const Campaign = adsSdk.Campaign; const account = new AdAccount('act_'); account.getCampaigns([Campaign.Fields.name], { limit: 2 }) .then((campaigns) => { if (campaigns.length >= 2 && campaigns.hasNext()) { return campaigns.next(); } else { Promise.reject( new Error('campaigns length < 2 or not enough campaigns') ); } }) .then((campaigns) => { if (campaigns.hasNext() && campaigns.hasPrevious()) { return campaigns.previous(); } else { Promise.reject( new Error('previous or next is not true') ); } return campaigns.previous(); }) .catch((error) => { }); ``` -------------------------------- ### Get Node Path Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Use getNodePath to obtain the API path for the object, which typically corresponds to its ID. This is used internally for API requests. ```javascript getNodePath(): string ``` ```javascript campaign.getNodePath(); // Returns campaign ID ``` -------------------------------- ### Get Campaign Performance Insights Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Fetches campaign-level performance metrics including spend, impressions, clicks, and CPC for a specified date range. ```javascript // Get campaign performance const insights = await campaign.getInsights( [ adsSdk.AdsInsights.Fields.spend, adsSdk.AdsInsights.Fields.impressions, adsSdk.AdsInsights.Fields.clicks, adsSdk.AdsInsights.Fields.cpc, adsSdk.AdsInsights.Fields.actions ], { date_start: '2024-01-01', date_stop: '2024-12-31', level: 'campaign' // Get campaign-level data } ); let totalSpend = 0; insights.forEach(row => { console.log(`Date: ${row.date_start}`); console.log(` Spend: ${row.spend}`); console.log(` Impressions: ${row.impressions}`); console.log(` CPC: ${row.cpc}`); totalSpend += parseFloat(row.spend); }); console.log(`Total spend: ${totalSpend}`); ``` -------------------------------- ### Manual Pagination Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/cursor.md Demonstrates how to manually iterate through paginated results using a while loop and the `hasNext()` and `next()` methods. ```APIDOC ## Manual Pagination This section illustrates manual pagination through API results. It shows how to fetch an initial page of data and then iteratively fetch subsequent pages until all data has been retrieved. ### Method `getCampaigns([fields], { limit })` - Fetches a page of campaigns. `page.hasNext()` - Checks if there are more pages to fetch. `page.next()` - Fetches the next page of results. ### Example ```javascript let page = await account.getCampaigns([Campaign.Fields.name], { limit: 5 }); page.forEach(campaign => { console.log(campaign.name); }); while (page.hasNext()) { page = await page.next(); page.forEach(campaign => { console.log(campaign.name); }); } ``` ``` -------------------------------- ### Get Parent Object ID Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Use getParentId to retrieve the ID of the parent object associated with this object. An error is thrown if the parent ID has not been set. ```javascript getParentId(): string ``` -------------------------------- ### Batch Request for Multiple Objects Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/batch-api.md Illustrates how to use batch requests to fetch multiple objects efficiently. This is compared to the slower method of making individual requests. ```APIDOC ## GET Batch Request for Multiple Objects ### Description Fetches multiple objects in a single batch request, significantly reducing the number of network round-trips compared to individual requests. This is ideal for retrieving data for a list of IDs. ### Method GET ### Endpoint `[id]` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the object to retrieve. #### Query Parameters - **fields** (string) - Optional - A comma-separated list of fields to retrieve for the object. ### Request Example ```javascript const batch = new FacebookAdsApiBatch(api); const campaigns = []; campaignIds.forEach(id => { batch.add('GET', [id], { fields: 'name' }, undefined, response => campaigns.push(response.getContent()) ); }); await batch.execute(); ``` ### Response #### Success Response (200) - **response** (object) - The response object containing the content of the requested object. ``` -------------------------------- ### Read AdCreative Details Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Shows how to instantiate an AdCreative object and read its name and object type. ```javascript const creative = new adsSdk.AdCreative(''); await creative.read([adsSdk.AdCreative.Fields.name, adsSdk.AdCreative.Fields.object_type]); console.log(creative.name, creative.object_type); ``` -------------------------------- ### Bulk Create Ad Sets Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/batch-api.md Creates multiple ad sets within a campaign. Each ad set creation is added as a POST request to the batch. Success callbacks record the index and ID of the created ad set, while failure callbacks log specific ad set creation errors. ```javascript async function bulkCreateAdSets(api, campaignId, adSetConfigs) { const batch = new FacebookAdsApiBatch(api); const created = []; adSetConfigs.forEach((config, index) => { batch.add( 'POST', [campaignId, 'adsets'], config, undefined, (response) => { created.push({ index, id: response.getContent().id }); }, (response) => { console.error(`AdSet ${index} creation failed:`, response.getError()); } ); }); await batch.execute(); return created; } ``` -------------------------------- ### Handling RangeError in Cursor Pagination Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/errors.md Demonstrates how to safely navigate through paginated results and catch RangeError exceptions that occur when reaching the end or start of the pagination. ```javascript let page = await account.getCampaigns([Campaign.Fields.name]); try { if (page.hasNext()) { page = await page.next(); } else { // Safe: hasNext() checked first } } catch (error) { if (error instanceof RangeError) { console.log('Pagination ended'); } } ``` -------------------------------- ### Retrieve App ID Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api.md Call this method to get the app ID associated with the current access token. It returns a Promise that resolves to an object containing the app_id. ```javascript api.getAppID() .then(response => console.log('App ID:', response.app_id)) .catch(error => console.error(error)); ``` -------------------------------- ### Set Environment Variables for SDK Initialization Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/configuration.md Export essential environment variables for authentication and identification. These are commonly used for initializing the FacebookAdsApi. ```bash # Recommended environment variables export FACEBOOK_ACCESS_TOKEN= export FACEBOOK_PIXEL_ID= export FACEBOOK_APP_ID= export FACEBOOK_APP_SECRET= ``` -------------------------------- ### Get Graph API Base URL Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/facebook-ads-api.md Retrieve the base URL for standard Graph API requests. This is a static getter that returns the default Graph API endpoint. ```javascript const graphUrl = FacebookAdsApi.GRAPH; ``` -------------------------------- ### Initialize FacebookAdsApi with Environment Variable Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/configuration.md Initialize the FacebookAdsApi using the access token from an environment variable. This is a common practice for authenticating SDK requests. ```javascript const api = FacebookAdsApi.init(process.env.FACEBOOK_ACCESS_TOKEN); ``` -------------------------------- ### Get Ad Account Insights Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/ad-account.md Retrieve performance insights for campaigns or ads under an ad account. Specify metrics and query parameters like date range and level. ```javascript account.getInsights( [adsSdk.AdsInsights.Fields.spend, adsSdk.AdsInsights.Fields.impressions], { date_start: '2024-01-01', date_stop: '2024-12-31', level: 'campaign' } ) .then(insights => { insights.forEach(row => { console.log('Spend:', row.spend, 'Impressions:', row.impressions); }); }); ``` -------------------------------- ### Processing as You Go (Memory Efficient) Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/cursor.md An efficient method for processing data as it's fetched, without storing the entire dataset in memory, suitable for very large results. ```APIDOC ## Processing as You Go (Memory Efficient) This approach is memory-efficient as it processes each item individually as it is fetched, avoiding the need to load the entire dataset into memory. This is ideal for extremely large result sets. ### Method `account.getCampaigns(fields)` - Fetches campaigns with specified fields. `page.hasNext()` - Checks if there are more pages. `page.next()` - Fetches the next page. ### Example ```javascript async function processCampaigns(account) { let page = await account.getCampaigns([adsSdk.Campaign.Fields.name]); do { for (const campaign of page) { console.log(`Processing: ${campaign.name}`); } if (page.hasNext()) { page = await page.next(); } else { break; } } while (true); } ``` ``` -------------------------------- ### Export All Data Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Use exportAllData to get all fields currently set on the object, regardless of whether they have been modified. This provides a complete snapshot of the object's current state. ```javascript exportAllData(): Object ``` ```javascript const campaign = new Campaign(''); await campaign.read([Campaign.Fields.id, Campaign.Fields.name]); const allData = campaign.exportAllData(); // Returns all fields that were fetched ``` -------------------------------- ### Constructor Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/batch-api.md Initializes a new FacebookAdsApiBatch instance. It can take an API instance and optional global success and failure callbacks. ```APIDOC ## Constructor ```javascript new FacebookAdsApiBatch( api: FacebookAdsApi, successCallback?: Function, failureCallback?: Function ) ``` ### Parameters - **api** (FacebookAdsApi) - Required - API instance for making requests - **successCallback** (Function) - Optional - Global callback for all successful requests - **failureCallback** (Function) - Optional - Global callback for all failed requests ### Example ```javascript const adsSdk = require('facebook-nodejs-business-sdk'); const api = adsSdk.FacebookAdsApi.init(''); const batch = new adsSdk.FacebookAdsApiBatch(api); ``` ``` -------------------------------- ### getEdge Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Initializes a Cursor to paginate through edge/relationship objects. It can fetch the first page immediately or return a cursor for later population. ```APIDOC ## getEdge ### Description Initialize a Cursor to paginate through edge/relationship objects. ### Method `getEdge` ### Parameters #### Path Parameters None #### Query Parameters - **targetClass** (Function) - Required - Constructor for related objects (Campaign, Ad, etc.) - **fields** (Array) - Optional - Fields to fetch on related objects - **params** (Object) - Optional - Query parameters (limit, filtering, etc.) - **fetchFirstPage** (boolean) - Optional - If true, fetch first page immediately; if false, return cursor without fetching - **endpoint** (string) - Optional - Edge name (e.g., 'campaigns', 'adsets') - **basePath** (string) - Optional - Base path override ### Request Example ```javascript // With immediate fetch const campaigns = await account.getEdge( Campaign, [Campaign.Fields.name, Campaign.Fields.status], { limit: 10 }, true, 'campaigns' ); // Without immediate fetch const cursor = account.getEdge(Campaign, [], {}, false, 'campaigns'); // Later: populate cursor const campaigns = await cursor.next(); ``` ### Response #### Success Response - **Cursor | Promise** - If fetchFirstPage=true: Promise resolving to populated Cursor; If fetchFirstPage=false: Cursor (not yet populated) #### Response Example (See Request Example for usage context) ``` -------------------------------- ### Batch Fetch Multiple Objects Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/README.md Retrieve multiple campaign objects by their IDs, specifying the fields to fetch for each campaign. This is useful for getting a collection of campaigns with specific details. ```javascript const campaignIds = ['', '', '']; const campaigns = await adsSdk.Campaign.getByIds( campaignIds, [adsSdk.Campaign.Fields.id, adsSdk.Campaign.Fields.name, adsSdk.Campaign.Fields.daily_budget] ); campaigns.forEach(campaign => { console.log(`${campaign.name}: $${campaign.daily_budget / 100}`); }); ``` -------------------------------- ### Get Edge without Immediate Fetch Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/abstract-crud-object.md Initializes a Cursor to paginate through edge/relationship objects without fetching the first page immediately. Allows for deferred fetching of related objects. ```javascript const cursor = account.getEdge(Campaign, [], {}, false, 'campaigns'); // Later: populate cursor const campaigns = await cursor.next(); ``` -------------------------------- ### Performance Considerations - Limit Parameter Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/cursor.md Explains how to use the `limit` parameter to control the page size for more efficient data fetching. ```APIDOC ## Performance Considerations - Limit Parameter To optimize performance, you can control the number of items returned per page by setting the `limit` parameter. This can reduce the number of requests needed and the amount of data transferred. ### Parameters - **limit** (integer) - Optional - The number of items to retrieve per page. Minimum: 10, Maximum: 500 (this range can vary by endpoint). ### Example ```javascript // Fetch 100 items per page (more efficient than default) const campaigns = await account.getCampaigns( [Campaign.Fields.name], { limit: 100 } ); ``` ``` -------------------------------- ### Manage and Read Ad Details Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Demonstrates how to read specific fields of an Ad and update its name. It also shows how to retrieve performance insights for a given date range. ```javascript const ad = new adsSdk.Ad(''); await ad.read([adsSdk.Ad.Fields.name, adsSdk.Ad.Fields.effective_status]); ad.name = 'Updated Ad Name'; await ad.update(); // Get performance insights const insights = await ad.getInsights( [adsSdk.AdsInsights.Fields.spend, adsSdk.AdsInsights.Fields.impressions], { date_start: '2024-01-01', date_stop: '2024-12-31' } ); insights.forEach(row => { console.log(`Spend: ${row.spend}, Impressions: ${row.impressions}`); }); ``` -------------------------------- ### AdSet Inherited Methods Source: https://github.com/facebook/facebook-nodejs-business-sdk/blob/main/_autodocs/api-reference/common-objects.md Demonstrates common CRUD and edge-related methods available for AdSet objects. ```javascript adSet.read([AdSet.Fields.id, AdSet.Fields.name]) adSet.update({ [AdSet.Fields.daily_budget]: 50000 }) adSet.delete() adSet.getAds([...]) // Get child ads adSet.createAd([...], {...}) // Create child ad adSet.getInsights([...], {...}) // Get performance data ```