NEW:Agent is hereTry free →

How to Use the Facebook Campaign Builder API Integration: A Step-by-Step Guide

16 min read
Share:
Featured image for: How to Use the Facebook Campaign Builder API Integration: A Step-by-Step Guide
How to Use the Facebook Campaign Builder API Integration: A Step-by-Step Guide

Article Content

The Meta Marketing API is one of those tools that looks intimidating from the outside but clicks into place quickly once you understand the underlying structure. If you manage Meta advertising at any real scale, you already know that Ads Manager has its limits. Manually building campaigns one by one, uploading creatives individually, and switching between tools burns hours that should go toward strategy.

The Facebook Marketing API (now officially the Meta Marketing API) changes that equation entirely. It lets you build, launch, and manage campaigns programmatically, giving you precise control over every campaign, ad set, and creative without touching the Ads Manager interface.

This guide walks you through the full integration process, from setting up your developer credentials to making your first API call that creates a live campaign. Whether you are a performance marketer looking to automate repetitive build work, a developer integrating ad creation into a broader martech stack, or a media buyer who wants to stop babysitting manual workflows, this tutorial gives you a concrete, working path forward.

Before diving in, here is the mental model that makes everything else easier. The Meta Marketing API follows a strict three-level hierarchy: Campaign (objective and budget type) sits at the top, Ad Set (targeting, budget, schedule, placement) sits in the middle, and Ad (creative and destination URL) sits at the bottom. Every API call you make fits into one of these three levels. Keep that structure in mind and the rest of the guide will make immediate sense.

For teams who want all of this without writing a single line of code, platforms like AdStellar handle the entire API layer for you, letting you build and launch campaigns through a clean interface while the AI manages the integration underneath. But understanding the API itself makes you a sharper marketer regardless of which tools you use.

Step 1: Set Up Your Meta Developer App and Get API Access

Everything starts at developers.facebook.com. Navigate there and click "Create App." You will be prompted to choose an app type. Select Business as your app type. This is the correct choice for any integration involving the Marketing API, and it unlocks the right permission sets from the start.

Once your app is created, you land on the App Dashboard. From here, click "Add Product" and find Marketing API in the product catalog. Add it to your app. This step is what connects your developer app to Meta's advertising infrastructure.

Next, locate your App ID and App Secret from the App Dashboard under Settings > Basic. Copy these somewhere secure. You will need both for the authentication steps ahead.

Now, the part that catches many people off guard: your app needs to be connected to a verified business. Navigate to Meta Business Manager (business.facebook.com) and verify your business if you have not already. Then go to Business Settings > Apps and link your newly created developer app to your Business Portfolio. This connection is what gives your app access to real ad accounts and unlocks higher API rate limits.

Common pitfall: Using a personal Facebook account instead of a Business Manager account will severely limit your API permissions and cap your daily rate limits. Any production integration needs to live under a proper Business Manager setup. If you are evaluating whether to build on the API directly or use a Facebook ads campaign builder software instead, this setup complexity is one of the key tradeoffs to weigh.

One more thing to configure while you are in the App Dashboard: set your app to Live mode rather than Development mode. Development mode restricts API access to app admins and testers only, which is fine for initial testing but will block access when you try to connect real ad accounts.

Success indicator: Your app shows "Marketing API" in the Products section with an Active status, and the app is linked to a verified Business Portfolio in Business Manager.

Step 2: Generate a Long-Lived Access Token with the Right Permissions

Authentication is where most first-time integrations stumble. Let's walk through it correctly from the beginning.

Inside the Meta Developer portal, open the Graph API Explorer. This is a built-in tool that lets you generate tokens and test API calls directly in the browser. From the Explorer, click "Generate Access Token." This creates a short-lived User Access Token that expires in about an hour, which is fine for testing but useless for production.

When generating the token, you need to request the right permissions. Select all of the following scopes: ads_management, ads_read, business_management, and pages_read_engagement. Missing even one of these will cause specific API calls to fail later. The ads_management scope is the most critical: without it, every campaign creation call will return a permission error.

To convert your short-lived token into a long-lived token, make a GET request to this endpoint:

graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=YOUR_APP_ID&client_secret=YOUR_APP_SECRET&fb_exchange_token=YOUR_SHORT_LIVED_TOKEN

The response will include a new token that lasts about 60 days. Better, but still not ideal for automated workflows.

For production use, the right approach is a System User token. Inside Business Manager, go to Business Settings > System Users and create a new System User. Assign it Admin access, then generate a token directly from the System User profile. System User tokens do not expire, are not tied to any individual employee's account, and survive staff changes. This is the standard for any automated Facebook campaign creation workflow.

Storage matters. Never hardcode tokens in your codebase or commit them to version control. Store them as environment variables or use a dedicated secrets manager. A leaked token gives anyone full access to your ad accounts.

Success indicator: A GET request to graph.facebook.com/me?access_token=YOUR_TOKEN returns your account name and ID without an error. That confirms your token is valid and has the correct permissions attached.

Step 3: Retrieve Your Ad Account ID and Validate Account Access

Before you can create anything, you need to confirm exactly which ad account you are working with and that your token has the right level of access to it.

Make a GET request to graph.facebook.com/me/adaccounts. This returns a list of all ad accounts your token can access, along with key fields for each one. The most important thing to notice here is the account ID format: it always appears as act_XXXXXXXXXX, with the "act_" prefix included. You will use this exact format in every subsequent API call. Omitting the prefix is a common mistake that returns a confusing error.

Within the response, check the account_status field for your target account. A value of 1 means the account is active. Other values indicate restricted, disabled, or pending review states. If your account is not returning a status of 1, resolve that in Ads Manager before proceeding. The API will not let you create campaigns on a restricted account.

Also pull the currency and timezone fields from the response. These matter more than they seem. The currency field tells you which unit system your budget values need to follow (more on that in Step 5), and the timezone affects how scheduled start and end times are interpreted by the API.

If you are working with a client's ad account rather than your own, there is an additional step. The System User you created in Step 2 needs to be explicitly granted Admin access to that specific ad account inside Business Manager. Go to Business Settings > Ad Accounts, select the account, and add the System User as an admin. Teams managing multiple client accounts at scale often find that a dedicated Facebook campaign builder for agencies handles these permission structures more efficiently than raw API management.

Success indicator: The adaccounts response lists your target account with account_status equal to 1, and the account ID appears in the act_XXXXXXXXXX format you will use going forward.

Step 4: Create the Campaign Object via the API

Now the actual campaign building begins. This is where the facebook campaign builder API integration starts to feel real.

Make a POST request to graph.facebook.com/act_ACCOUNT_ID/campaigns. The required fields for this call are: name, objective, status, and special_ad_categories.

The objective field is where many developers trip up by using outdated values. Meta has migrated to Outcome-Driven Ad Experiences (ODAX) objectives. The current valid values are: OUTCOME_AWARENESS, OUTCOME_TRAFFIC, OUTCOME_ENGAGEMENT, OUTCOME_LEADS, OUTCOME_APP_PROMOTION, and OUTCOME_SALES. Using legacy objective names like CONVERSIONS or LINK_CLICKS may trigger deprecation warnings or outright errors depending on which API version you are calling. Stick with the OUTCOME_ prefix naming convention for any new integration. Understanding how these objectives map to real business goals is covered in depth in guides on Facebook campaign optimization.

Set status to PAUSED during build and testing. This is important. A campaign set to ACTIVE at creation will begin spending immediately once ad sets and ads are attached. Build everything first, review it, then activate in Step 7.

The special_ad_categories field is required even if your campaign has no special category restrictions. If your ads do not fall under housing, employment, credit, or social issues categories, pass an empty array. Omitting this field entirely returns a validation error, which is frustrating when you do not know to expect it.

A note on API versioning: always specify a version in your endpoint URL. For example, use /v20.0/act_ACCOUNT_ID/campaigns rather than calling the unversioned endpoint. Meta retires older API versions on a rolling schedule, typically after about two years. Version-pinning your calls protects your integration from unexpected breaking changes when Meta updates the API.

On success, the API returns a response with a single id field containing a numeric campaign ID. Save this immediately. You will reference it in the next step when creating ad sets.

Success indicator: The POST response contains an id field with a numeric campaign ID. No error fields in the response body.

Step 5: Build Ad Sets with Targeting, Budget, and Schedule

The ad set is where most of the strategic configuration lives. Targeting, budget, schedule, optimization goal: all of it gets defined here.

POST to graph.facebook.com/act_ACCOUNT_ID/adsets with the following required fields: name, campaign_id (the ID from Step 4), daily_budget or lifetime_budget, billing_event, optimization_goal, targeting, and status.

The budget field is the single most common source of errors for developers new to the API. All budget values must be in the smallest currency unit. For USD accounts, that means cents. A $50 daily budget must be passed as 5000, not 50. For GBP accounts, use pence. Check the currency field you retrieved in Step 3 and convert accordingly before every budget call.

Also note that daily_budget and lifetime_budget are mutually exclusive. You cannot pass both. Choose one based on whether you want a capped total spend or a recurring daily limit.

The targeting object is a nested JSON structure. At minimum, include geo_locations (with a country or city array), age_min, age_max, and genders. A basic targeting object for a US audience aged 25 to 45 looks like this in structure: geo_locations with countries set to US, age_min set to 25, age_max to 45.

For Advantage+ audience, Meta's AI-driven targeting option, pass a simplified targeting object with just the geo_locations and set targeting_automation to enabled. This hands targeting decisions over to Meta's algorithm, which often performs well for conversion-focused campaigns. For a deeper look at how automated targeting compares to manual configuration, the Facebook campaign builder vs manual breakdown covers the key performance tradeoffs.

Control your flight dates using start_time and end_time fields, formatted as Unix timestamps. If you want the ad set to run indefinitely, omit end_time. If you are using a lifetime budget, end_time is required.

Set billing_event to IMPRESSIONS and optimization_goal to match your campaign objective. For OUTCOME_SALES, use OFFSITE_CONVERSIONS as the optimization goal. For OUTCOME_TRAFFIC, use LINK_CLICKS or LANDING_PAGE_VIEWS.

Success indicator: The response contains an ad set ID and a review_feedback field that is empty, indicating no immediate policy flags on your targeting configuration.

Step 6: Upload Creatives and Create the Ad Object

Creating the ad involves three sequential sub-steps: upload the asset, create the AdCreative object, then create the Ad object that ties everything together.

Step 6a: Upload your image or video asset. For images, POST to graph.facebook.com/act_ACCOUNT_ID/adimages with the image file included as multipart form data. The response returns an image hash, a unique identifier for that asset. For videos, POST to graph.facebook.com/act_ACCOUNT_ID/advideos and capture the video ID from the response. Save whichever identifier applies to your creative.

Before uploading, verify your image meets Meta's size requirements. For single image feed ads, the minimum is 1080x1080 pixels for square format. Uploading an image that does not meet the size or aspect ratio requirements returns a creative validation error that can be confusing if you do not know to expect it. Pre-check dimensions before making the upload call.

Step 6b: Create the AdCreative object. POST to graph.facebook.com/act_ACCOUNT_ID/adcreatives with your asset reference (the image hash or video ID), plus the following fields: headline, body (ad copy), call_to_action (with type and link), and link (your destination URL). The structure nests these fields inside an object_story_spec or asset_feed_spec depending on the ad format you are building.

The response returns an AdCreative ID. Save it.

Step 6c: Create the Ad object. POST to graph.facebook.com/act_ACCOUNT_ID/ads with three key references: adset_id (from Step 5), creative (containing your AdCreative ID), and status set to PAUSED. The ad object is what ties the targeting and budget configuration from the ad set to the visual and copy from the creative. It is the final piece of the hierarchy. Teams running high-volume creative testing often use Facebook ads bulk campaign creation tools to handle this assembly step across hundreds of ad variations simultaneously.

After creation, check the effective_status field on the ad object. PENDING_REVIEW means the ad is in Meta's automated review queue, which is normal. ACTIVE means it passed review immediately. DISAPPROVED means there is a policy issue with the creative or destination URL that needs to be resolved before the ad can run.

Success indicator: The ad object shows effective_status as PENDING_REVIEW or ACTIVE. A DISAPPROVED status requires reviewing the rejection reason in the ad's review_feedback field and addressing the specific policy flag before proceeding.

Step 7: Activate the Campaign and Monitor Performance via API

With your campaign, ad sets, and ads all built in PAUSED status, you are ready to go live.

Activate the campaign by making a POST request to graph.facebook.com/CAMPAIGN_ID with the body parameter status set to ACTIVE. This single call flips the campaign live. The ad sets and ads beneath it will start running according to their own status settings, so confirm those are set to ACTIVE as well if you want everything to start immediately.

Once the campaign is live, pull performance data using the Insights endpoint. Make a GET request to graph.facebook.com/act_ACCOUNT_ID/insights with a fields parameter listing the metrics you want: impressions, clicks, spend, cpc, ctr, cpm, reach, and actions (for conversion data). The Insights API is flexible and returns only the fields you request, so be specific.

For date ranges, use the date_preset parameter for quick windows like last_7d, last_30d, or yesterday. For custom date ranges, pass a time_range object with start and end date strings in YYYY-MM-DD format.

For large data pulls covering long date ranges or many campaigns at once, use async jobs rather than synchronous requests. Submit an async insights job, then poll the job status endpoint until it returns a completed state, then fetch the results. This avoids timeout errors and rate limit pressure on large accounts. Once your data pipeline is stable, the next challenge is acting on what it tells you — strategies for scaling Facebook advertising campaigns effectively depend heavily on having reliable performance data flowing in at the right cadence.

For ongoing monitoring, set up a scheduled polling job that pulls insights at a regular cadence, hourly or daily depending on your reporting needs, and feeds the data into your reporting layer or dashboard. If you are managing many campaigns simultaneously, use batch requests to pull insights for multiple campaigns in a single API call. The Meta API supports up to 50 calls per batch, which significantly reduces rate limit consumption.

Keep an eye on the rate limit headers returned in every API response. If you start approaching your limit, the response headers will reflect it. Exceeding the limit returns error code 17, and calls will fail until the limit resets.

Success indicator: The insights endpoint returns spend data that matches what you see in Ads Manager for the same date range. If the numbers align, your integration is reading the correct account and your authentication is working as expected.

Putting It All Together: From API Calls to Scalable Ad Operations

You now have a complete path from developer credentials to a live, monitored campaign built entirely through the Meta Marketing API. The core flow is always the same: authenticate, create a campaign, build ad sets with targeting and budget, upload and attach creatives, then activate. Once that loop works, you can automate it, templatize it, and scale it across dozens of campaigns without touching Ads Manager manually.

A few things to keep in mind as you move into production. Always version-pin your API calls to a specific Graph API version to avoid breaking changes when Meta updates the platform. Monitor your rate limit headers in every response, and build retry logic into your integration for when limits are hit. Use System User tokens rather than personal tokens for any automated workflow. And test every new campaign build in PAUSED status before activating, so you catch configuration errors before they cost you budget.

For teams who want this level of campaign control without managing API infrastructure, AdStellar handles the entire integration layer. The AI Campaign Builder analyzes your past performance, ranks every creative and audience by real metrics, and builds complete Meta campaigns in minutes. The Bulk Ad Launch feature generates hundreds of ad variations across creatives, headlines, and audiences, then pushes them live in clicks rather than hours. The Winners Hub surfaces your best-performing combinations with real ROAS, CPA, and CTR data so you always know what to scale next.

You get the programmatic power of the API without the engineering overhead. Start Free Trial With AdStellar and be among the first to launch and scale your ad campaigns faster with an intelligent platform that automatically builds and tests winning ads based on real performance data.

Start your 7-day free trial

Ready to create and launch winning ads with AI?

Join hundreds of performance marketers using AdStellar to generate ad creatives, launch hundreds of variations, and scale winning Meta ad campaigns.