Skip to main content
Home/Meta Ads Playbook
Free Guide

The Engineer's Playbook for Meta Ads Automation

For developers and growth teams who run Meta ads. This guide covers everything from getting your first API token to scaling winning campaigns with the meta-ads-cli tool. No fluff. Just the steps.

What this guide covers.

Six topics: OAuth setup, audience segmentation, budget allocation, creative testing, scaling rules, and API error reference.

STEP 01

OAuth Setup

Create your Meta developer app and generate a long-lived API token step by step.

STEP 02

Audience Segmentation

Interest targeting, custom audiences, lookalikes, and broad targeting in YAML.

STEP 03

Budget Allocation

A 20/60/20 framework for splitting spend across testing, scaling, and retention.

STEP 04

Creative Testing

Run 3 variants per ad set, change one variable at a time, judge at $50 spend.

STEP 05

Scaling Rules

Four signals that tell you when a campaign is ready to scale, and how to do it.

STEP 06

API Error Reference

The five most common Meta API errors, what causes them, and how to fix them.

Step 1. Get your Meta access token.

Short-lived tokens expire in 2 hours. Always exchange for a long-lived token before using in production. Long-lived tokens last 60 days.

  1. 1

    Create a Meta developer app

    Go to developers.facebook.com and create a new app. Select app type: Business.

  2. 2

    Open Graph API Explorer

    Go to developers.facebook.com/tools/explorer. Select your app from the dropdown.

  3. 3

    Request permissions

    Add these permissions: ads_management, pages_read_engagement, pages_show_list.

  4. 4

    Generate your access token

    Click "Generate Access Token" and authorize. Copy the token to your .env file as META_ACCESS_TOKEN.

  5. 5

    Exchange for a long-lived token

    Short-lived tokens expire in 2 hours. Exchange immediately:

    curl "https://graph.facebook.com/v21.0/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"

    Long-lived tokens last approximately 60 days. Add a calendar reminder to renew.

Step 2. Build audiences that convert.

Start with interest targeting to prove creative, then expand to lookalikes once you have 1,000 conversions in your pixel.

Interest Targeting

Best for cold audiences. Use Meta interest IDs to reach people by behavior and interests. Start with 3-5 tightly related interests. Avoid stacking unrelated ones.

Custom Audiences

Upload your customer list or use pixel data to retarget site visitors. Best for re-engagement campaigns. Requires a privacy-compliant data upload.

Lookalike Audiences

Meta finds users who resemble your best customers. Requires a source audience of at least 100 people. 1% lookalike is most precise. 5-10% casts a wider net.

Broad Targeting

Age, gender, and location only. Works well for campaigns with large budgets where Meta's algorithm has enough signal. Not recommended under $100/day.

Example targeting block in your campaign YAML:

ad_set:
  targeting:
    age_min: 25
    age_max: 45
    genders: [0]          # 0 = all
    countries: ["US", "CA"]
    interests:
      - id: "6003139266461"
        name: "Fitness and wellness"
      - id: "6004034009990"
        name: "Sports nutrition"
    platforms: ["facebook", "instagram"]
    instagram_positions: ["stream", "story", "reels"]

Find interest IDs by searching the Meta API: GET /v21.0/search?type=adinterest&q=fitness&access_token=YOUR_TOKEN

Step 3. Allocate budget across campaigns.

Use a 20/60/20 framework: 20% testing new creatives, 60% scaling winners, 20% retargeting existing visitors and customers.

20%

Testing

New creatives, new audiences, new objectives. Low spend until a winner emerges.

60%

Scaling

Proven winners with ROAS above 2.5x. Expand budget incrementally, not all at once.

20%

Retention

Retargeting past visitors and existing customers. Higher conversion rate, lower CAC.

Budget is set in cents in your YAML

ad_set:
  daily_budget: 1000     # $10.00/day
  daily_budget: 5000     # $50.00/day
  daily_budget: 10000    # $100.00/day

Meta requires budget in the smallest currency unit. USD: cents. CAD: cents. GBP: pence.

Step 4. Test creatives systematically.

Change one variable per test. Wait for $50 in spend before judging. The winner is the ad with the lowest cost-per-click.

Run 3 ad variants per ad set. Change one variable: image, headline, or primary text.

Do not judge performance before $50 in spend. Meta needs data to optimize delivery.

Winner = lowest CPC. Pause the losing variants. Put their budget behind the winner.

Once you have a CPC winner, test the next variable. Image first, then headline, then copy.

Example: 3-creative test in one campaign YAML

ads:
  - name: "Ad A - Before After Image"
    image: ./images/before-after.png
    primary_text: "Lose 20 lbs in 90 days. Guaranteed."
    headline: "FitCommit AI"
    cta: LEARN_MORE
    link: "https://fitcommit.ai"

  - name: "Ad B - App Screenshot"
    image: ./images/app-screenshot.png
    primary_text: "Lose 20 lbs in 90 days. Guaranteed."
    headline: "FitCommit AI"
    cta: LEARN_MORE
    link: "https://fitcommit.ai"

  - name: "Ad C - Lifestyle Image"
    image: ./images/lifestyle.png
    primary_text: "Lose 20 lbs in 90 days. Guaranteed."
    headline: "FitCommit AI"
    cta: LEARN_MORE
    link: "https://fitcommit.ai"

Same copy and CTA. Only the image changes. This isolates the creative variable.

Step 5. Know when and how to scale.

Scale only when all four signals are green: ROAS above 2.5x, stable CPM, frequency below 3.0, audience saturation below 50%.

Four signals to scale

ROAS above 2.5x

Return on ad spend must exceed 2.5x for at least 7 days before scaling. Short-term spikes are noise.

Stable CPM

Cost per 1,000 impressions should not be rising week over week. Rising CPM signals audience exhaustion.

Frequency below 3.0

Average impressions per person. Above 3.0, people are seeing the same ad too many times. Diminishing returns accelerate.

Audience saturation below 50%

Available audience estimate in Meta Ads Manager. Above 50% reached, performance degrades. Widen targeting or find new segments.

Two ways to scale

Budget increase

Increase daily_budget by 20% every 2-3 days. Larger jumps reset the learning phase and can spike costs. Gradual is safer.

Duplicate the ad set

Create a new ad set with the same creative and targeting but a higher starting budget. The original keeps running. The duplicate starts fresh.

Common API errors and how to fix them.

Five errors account for most Meta API failures: token expiry, invalid parameters, billing issues, policy violations, and rate limits.

CodeTypeCauseFix
190OAuthExceptionAccess token expired or invalidRegenerate your token in Graph API Explorer and exchange for a long-lived token
100Invalid ParameterMalformed YAML or unsupported field valueRun meta-ads validate first. Check objective and optimization_goal are a valid pair
1487390Billing ErrorAd account has no valid payment methodAdd a payment method in Meta Business Manager under Billing settings
368Policy ViolationAd creative or targeting violates Meta advertising policiesReview ad copy and images against Meta Advertising Standards. Remove restricted claims
17Rate LimitToo many API calls in a short windowWait 15-30 minutes before retrying. Batch campaign creation into off-peak hours

Automate everything in this guide with one command.

meta-ads-cli is open source, MIT licensed. Install with pip. Define your campaign in YAML. Deploy in seconds.

Install the CLI, copy the example config, and deploy your first campaign in under 10 minutes.

pip install meta-ads-cli
cp campaign.example.yaml campaign.yaml
meta-ads validate --config campaign.yaml
meta-ads create --config campaign.yaml --dry-run
meta-ads create --config campaign.yaml

Campaigns are created as PAUSED by default. Review in Ads Manager, then activate when ready with meta-ads activate <campaign-id>.

View on GitHub

Frequently asked questions.

What is meta-ads-cli?

meta-ads-cli is an open source Python command-line tool that lets you create and manage Meta (Facebook and Instagram) ad campaigns from a YAML configuration file. One YAML file defines your campaign, ad set, targeting, and ads. One command deploys it. Built by Attainment.

Do I need a Meta developer account?

Yes. You need a Meta for Developers account to create an app and generate an API access token. The setup takes about 10 minutes. Full instructions are in Step 1 of this guide.

How long do Meta API tokens last?

Short-lived tokens from Graph API Explorer expire after about 2 hours. Long-lived tokens last approximately 60 days. Always exchange for a long-lived token before using in production. Set a calendar reminder to renew before they expire.

Why is daily_budget set in cents?

The Meta Marketing API requires budget values in the smallest currency unit. For USD, that is cents. So 1000 equals $10.00 per day. This matches how the Meta API works natively and avoids any conversion layer in the tool.

What if I hit a rate limit error (code 17)?

Wait 15 to 30 minutes before retrying. If you hit this frequently, reduce the frequency of your API calls or batch campaign creation into off-peak hours. The CLI includes confirmation prompts before creation to prevent accidental duplicate calls.

Need help setting this up?

We build and manage Meta Ads automation systems for growth teams.

Book a Discovery Call

Ready to automate your Meta ads?

Book a call to see how Attainment builds and manages Meta Ads automation for your team.