首页 AI Build a Facebook Campaign Creation Pipeline with Codex (2026): Marketing API v27.0, Idempotency Keys, Dry Runs and Tests

Build a Facebook Campaign Creation Pipeline with Codex (2026): Marketing API v27.0, Idempotency Keys, Dry Runs and Tests

Use OpenAI Codex to build a Facebook campaign creation pipeline on Marketing API v27.0: paused objects, idempotency keys, backoff, dry runs, tests and CI.

Last updated: 16 November 2026. Meta, Anthropic and OpenAI documentation checked that day.

Codex is at its best when the output is code you can test. That makes a campaign creation pipeline a good fit: a repo that turns a reviewed plan into paused Facebook campaigns, ad sets, creatives and ads through the Marketing API, with dry runs, tests and CI. This guide walks through what to ask Codex for and what we keep in the final code. For the overall Codex workflow, see Codex Facebook ads end-to-end workflow (Chinese).

Pipeline stages

StageCode Codex writesCheck before moving on
Planplan.json schema + validatorBudgets in cents, countries, special ad categories
Clientmeta_api.py with backoff + idempotencyUnit tests with mocked responses
Dry run–dry-run prints every payloadHuman reads the payloads
Createcreate_paused.pyEverything PAUSED, IDs saved
Reviewids.json → Ads Manager linksMedia buyer activates
Stages of a Codex-built Facebook campaign creation pipeline

Set the rules first: AGENTS.md

Codex reads AGENTS.md files before it starts work, from the global file down to the current directory (AGENTS.md). Put the non-negotiables there so every task inherits them:

# AGENTS.md  (repo root) - rules Codex reads before every task
## Meta ads automation rules
- Only touch ad accounts listed in accounts.allowlist (our own / client-authorised).
- Read tokens from env vars (META_SYSTEM_USER_TOKEN, META_ADS_MCP_TOKEN). Never print,
  log or commit them. Never put them in prompts.
- Create every campaign, ad set and ad with status=PAUSED. Never activate anything.
- Never raise a daily budget by more than 20% in one change; budgets are in cents.
- Always send X-Client-Idempotent-Key on create calls; reuse it on retries.
- Respect rate limits: back off on error codes 4, 17, 613, 80000-80014.
- Run `pytest -q` and `python -m scripts.dry_run` before proposing changes.
- Ad copy must follow Meta Advertising Standards; flag health, finance,
  employment, housing, politics and gambling for human review.

Stage 1–2: the API client

Ask Codex for a small client rather than a large SDK wrapper. The parts that matter are environment-variable tokens, backoff on Meta’s throttle codes, and the X-Client-Idempotent-Key header. Meta supports idempotency keys on campaign, ad set, ad and ad creative creation; keys last 7 days and are scoped to the ad account (idempotent requests).

# .env  (add .env to .gitignore; never commit or paste tokens into a prompt)
META_API_VERSION=v27.0
META_AD_ACCOUNT_ID=act_<AD_ACCOUNT_ID>
META_PAGE_ID=<PAGE_ID>
META_SYSTEM_USER_TOKEN=<SYSTEM_USER_ACCESS_TOKEN>
# meta_api.py - minimal Marketing API client (Python 3.10+, pip install requests)
import os, time, json, uuid, requests

API = "https://graph.facebook.com/" + os.environ.get("META_API_VERSION", "v27.0")
TOKEN = os.environ["META_SYSTEM_USER_TOKEN"]          # from env / secret manager only
ACT = os.environ["META_AD_ACCOUNT_ID"]                # e.g. act_1234567890
THROTTLE = {4, 17, 613, 80000, 80003, 80004, 80014}   # rate-limit codes in Meta's docs

def call(method, path, params=None, data=None, idem_key=None, tries=5):
    headers = {"X-Client-Idempotent-Key": idem_key} if idem_key else {}
    for attempt in range(tries):
        r = requests.request(method, f"{API}/{path}", headers=headers, timeout=60,
                             params={**(params or {}), "access_token": TOKEN} if method == "GET" else None,
                             data={**(data or {}), "access_token": TOKEN} if method != "GET" else None)
        for h in ("X-Business-Use-Case-Usage", "X-Ad-Account-Usage", "X-FB-Ads-Insights-Throttle"):
            if h in r.headers:
                print(h, r.headers[h])                    # log usage, back off early
        body = r.json()
        err = body.get("error")
        if not err:
            return body
        if err.get("code") in THROTTLE or r.status_code >= 500:
            time.sleep(min(60 * 2 ** attempt, 900))      # exponential backoff
            continue                                     # same idem_key -> no duplicates
        raise RuntimeError(json.dumps(err))
    raise RuntimeError("rate limited: giving up, try later")

def key(run_id, name):
    """Stable idempotency key per object, so a retry never creates a duplicate."""
    return str(uuid.uuid5(uuid.NAMESPACE_URL, f"{ACT}/{run_id}/{name}"))

Stage 3: dry run, then create

The creation script builds every object as PAUSED. special_ad_categories is required on campaigns, and ad set budgets are in the smallest currency unit (create a campaign, create an ad set).

# create_paused.py - campaign -> ad set -> creative -> ad, everything PAUSED
import json
from meta_api import call, key, ACT
import os
RUN = "2026-11-16-us-traffic"

camp = call("POST", f"{ACT}/campaigns", data={
    "name": "PWM | US | Traffic | Nov",
    "objective": "OUTCOME_TRAFFIC",
    "status": "PAUSED",
    "special_ad_categories": json.dumps([]),      # required; declare a category if it applies
    "is_adset_budget_sharing_enabled": "0",
}, idem_key=key(RUN, "campaign"))

adset = call("POST", f"{ACT}/adsets", data={
    "name": "US | 25-54 | broad",
    "campaign_id": camp["id"],
    "daily_budget": "5000",                         # in cents of the account currency = 50.00
    "billing_event": "IMPRESSIONS",
    "optimization_goal": "LINK_CLICKS",
    "bid_strategy": "LOWEST_COST_WITHOUT_CAP",
    "targeting": json.dumps({"geo_locations": {"countries": ["US"]},
                             "age_min": 25, "age_max": 54}),
    "status": "PAUSED",
}, idem_key=key(RUN, "adset-us-broad"))

creative = call("POST", f"{ACT}/adcreatives", data={
    "name": "US | hook-A",
    "object_story_spec": json.dumps({
        "page_id": os.environ["META_PAGE_ID"],
        "link_data": {"message": "<approved primary text>",
                      "link": "https://www.example.com/landing",
                      "image_hash": "<IMAGE_HASH>",
                      "call_to_action": {"type": "LEARN_MORE"}}}),
}, idem_key=key(RUN, "creative-hook-A"))

ad = call("POST", f"{ACT}/ads", data={
    "name": "US | hook-A",
    "adset_id": adset["id"],
    "creative": json.dumps({"creative_id": creative["id"]}),
    "status": "PAUSED",                             # a human activates after review
}, idem_key=key(RUN, "ad-hook-A"))
print(camp["id"], adset["id"], creative["id"], ad["id"])

Then let Codex add a dry-run flag and tests in a workspace-write sandbox, with no live API calls. With the Python Codex SDK (Codex SDK):

# pip install openai-codex   (Python 3.10+)
from openai_codex import Codex, Sandbox

with Codex() as codex:
    thread = codex.thread_start(sandbox=Sandbox.workspace_write)   # no full access
    result = thread.run(
        "Read AGENTS.md. Add a --dry-run flag to create_paused.py that prints "
        "the payloads instead of calling the API, plus tests. Do not call the live API.")
    print(result.final_response)

The Python SDK package and API can change; check the SDK page before pinning it. A one-off request works just as well from the CLI.

v27.0 changes to watch

  • For eligible new ad sets, “Reach more people across other mobile devices” is on by default (targeting_automation.individual_setting.device stored as 1); set it to 0 to keep the old behaviour.
  • lookalike_spec.country and location_spec are rejected.
  • Product showcase may be applied by default to creatives; opt out through degrees_of_freedom_spec if needed.

Source: Marketing API v27.0 changelog. Our Chinese summary: Marketing API v27.0 更新解读.

Stage 4: handle limits like a production system

Error / limitCode or rulePipeline response
Per-account mutation QPS613 / 5044001, 100 QPSQueue writes, back off
Same object edited too fast613 / 4841018, 1 per 30sBatch edits per object
Ad set budget changes613 / 1487632, 4 per hourDon’t loop budget edits
Business use case limit80000–80014 familyRead X-Business-Use-Case-Usage
Timeout after POSTUnknown resultRetry with the same idempotency key
Marketing API rate limits and how a Codex pipeline should respond

See rate limiting. Apps in the development tier have far lower limits than Full Access apps, which need at least 500 Marketing API calls in 15 days with an error rate under 15% (authorization).

Stage 5: CI

Run tests and the dry run on every pull request; keep the live create step manual. If Codex reviews pull requests in CI, use openai/codex-action, which keeps the API key scoped to that step (Codex GitHub Action). Creative uploads are covered in Codex bulk creative upload (Traditional Chinese); daily reports in Codex daily reports (Chinese).

How PandaWM uses Claude, Codex and Facebook ad accounts to speed up client ad delivery

This guide focuses on Codex, but in day-to-day client work PandaWM combines Claude, Codex and Facebook business ad accounts to help companies going global move faster through the repetitive loop of account setup → campaign structure → creatives → reporting → budget changes, so media buyers spend their time on strategy and creative judgement.

  • Ad accounts: the client’s own Facebook ad account, or a business ad account opened compliantly through PandaWM’s account-opening service. The account belongs to the client and is never rented or shared.
  • Claude: reading long docs and reports, drafting media plans and ad copy, drafting campaign structures in a paused state through Meta’s ads MCP server, and rule-based anomaly checks.
  • Codex: writing and maintaining automation scripts (Marketing API, Insights reports, bulk uploads, budget rules) that run in a sandbox, on a schedule or in CI.
  • Human sign-off: anything that spends money (activating ads, raising budgets) is approved by a media buyer, and a person makes the final call on Meta policy and creative compliance.

This describes a service capability only. There are no prices or rebates here, and PandaWM is not an official partner of Meta, Anthropic or OpenAI. See Facebook ads account opening & management (PandaWM service page) for account opening and management.

FAQ

Why not let Codex call the API directly through MCP?

You can, with approvals, as in our config.toml guide. A script is better for repeatable bulk creation because it is testable and reviewable.

What happens if a create call times out?

Retry with the same idempotency key. Meta returns the original result instead of creating a duplicate.

Which token should the pipeline use?

A system user token with ads_management, assigned only to the ad accounts and Pages the pipeline needs.

Can the pipeline activate ads?

It can technically. We keep activation manual so a person checks budget, targeting and policy first.

Does Codex work in every country?

OpenAI services are only available in supported countries and territories; check OpenAI’s list.

Compliance note: Use every workflow in this guide only on ad accounts, Pages and pixels that your company owns or is formally authorised to manage, through Meta’s official Marketing API, the ads MCP server or Ads CLI, with Business Manager system users and least-privilege permissions. Respect Meta’s rate limits and Advertising Standards, and keep a human review step before anything that can spend money. PandaWM does not sell, rent, share or transfer ad accounts, Business Managers or API keys, does not help anyone bypass ad review, regional restrictions, KYC, business verification or payment controls, and is not an official partner of Meta, Anthropic or OpenAI. Claude and OpenAI services are only offered to customers in their supported countries and regions; the account holder should be an entity legitimately established and operating in a supported region.

Related guides

Talk to PandaWM: Facebook ad accounts + AI-assisted delivery

Tell us where your company is registered, your industry, target countries, landing page and expected monthly budget, and which part you want to automate first (account structure, creatives, reporting or budget rules). We pre-check eligibility and creatives, help you open a compliant Facebook business ad account, and build Claude or Codex workflows that run on your own accounts. We never sell, rent or share ad accounts.

WhatsApp: +852 5904 8602Telegram: @PANDA0134WeChat: szcwh99

PandaWM WeChat QR code szcwh99

Official sources

All official pages checked on 2026-11-16. API versions, tool names and permission requirements change; the official pages prevail.

本文来自网络,不代表熊猫出海立场。转载请注明出处: https://www.pandawm.com/blog/codex-facebook-marketing-api-campaign-creation-pipeline-en.html
上一篇
下一篇

作者: 熊猫出海编辑团队

熊猫出海(PandaWM)编辑团队,来自香港出海服务商熊猫出海,专注 Facebook、TikTok、Google 等海外广告开户与代投,以及 GEO/AI 搜索优化、多语言独立站建设。有Facebook白名单牌照户、TikTok加白户、Google G2认证户等核心资源 。

为您推荐

发表回复

联系我们

联系我们

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部