首页 AI Codex + TikTok Marketing API (2026): A Python Smart+ Pipeline with OAuth, Idempotent Creates and Rate-Limit Handling

Codex + TikTok Marketing API (2026): A Python Smart+ Pipeline with OAuth, Idempotent Creates and Rate-Limit Handling

Have Codex build a Python pipeline on TikTok Marketing API v1.3: auth_code to access token, Smart+ campaigns created as DISABLE, request_id, retries and tests.

Last updated: 16 November 2026. TikTok API for Business (v1.3), the TikTok for Business MCP Server, Anthropic and OpenAI documentation checked that day.

Agents are great for ad-hoc work, but repeatable campaign builds belong in code you can test and review. This guide shows how to have OpenAI Codex build a small Python pipeline on TikTok Marketing API v1.3 that creates Upgraded Smart+ campaigns safely. For the agent route through TikTok’s hosted MCP server, see Codex config.toml for the TikTok for Business MCP server.

Prerequisites

TikTok’s getting-started flow is: create a TikTok for Business account, register as a developer, create a developer app, get advertiser authorisation, authenticate, then make your first call (Get started). Only automate ad accounts your company owns or is authorised to manage.

The modules

ModuleWhat Codex writesKey rule
auth.pyauth_code → long-term access token, list advertisersauth_code is valid 1 hour and single-use
create_smart_plus.pyUpgraded Smart+ campaign createoperation_status DISABLE, request_id reused on retry
throttle.pyPer-ad 5-second spacing for Smart+ ad callsOne create/update/status per ad every 5 s
client.pyShared session, error codes, back-offCheck body code, not only HTTP status
tests/Payload and retry tests with mocksNever call the live API in tests
Python Smart+ pipeline modules Codex builds for TikTok Marketing API

Authentication

The advertiser authorisation redirect returns an auth_code that is valid for one hour and can be used once. Exchanging it gives a long-term access token that does not expire, but stops working if the advertiser revokes authorisation (Authentication).

# exchange the one-time auth_code (valid 1 hour) for a long-term access token
import os, requests
BASE = "https://business-api.tiktok.com/open_api/v1.3"
r = requests.post(f"{BASE}/oauth2/access_token/", json={
    "app_id": os.environ["TIKTOK_APP_ID"],
    "secret": os.environ["TIKTOK_APP_SECRET"],
    "auth_code": os.environ["TIKTOK_AUTH_CODE"],   # from the advertiser authorization redirect
}, timeout=30).json()
assert r["code"] == 0, r["message"]
token = r["data"]["access_token"]          # store in a secret manager, never in git
print("authorised advertisers:", r["data"].get("advertiser_ids"))

Creating a Smart+ campaign, switched off

Required fields are advertiser_id, request_id, objective_type and campaign_name; sales_destination is required for WEB_CONVERSIONS. operation_status defaults to ENABLE, so the pipeline always sends DISABLE (Create an Upgraded Smart+ campaign).

# create_smart_plus.py - Upgraded Smart+ campaign, created switched OFF
import os, random, requests
BASE = "https://business-api.tiktok.com/open_api/v1.3"
H = {"Access-Token": os.environ["TIKTOK_ACCESS_TOKEN"], "Content-Type": "application/json"}

def new_request_id():
    return str(random.getrandbits(63))       # string of a 64-bit int; reuse on retry

def create_campaign(advertiser_id, name, daily_budget, request_id=None):
    body = {
        "advertiser_id": advertiser_id,
        "request_id": request_id or new_request_id(),
        "objective_type": "WEB_CONVERSIONS",
        "sales_destination": "WEBSITE",       # required for WEB_CONVERSIONS
        "campaign_name": name,
        "operation_status": "DISABLE",        # default is ENABLE - never rely on it
        "budget_optimize_on": True,
        "budget_mode": "BUDGET_MODE_DYNAMIC_DAILY_BUDGET",
        "budget": float(daily_budget),        # account currency units
    }
    r = requests.post(f"{BASE}/smart_plus/campaign/create/", headers=H, json=body, timeout=60).json()
    if r["code"] != 0:
        raise RuntimeError(f'{r["code"]} {r["message"]} request_id={body["request_id"]}')
    return r["data"]

Spacing Smart+ ad calls

TikTok asks callers to limit create, update and status calls on a single Upgraded Smart+ ad to one every 5 seconds (TikTok MCP guide). A tiny helper does it:

# one Upgraded Smart+ ad: at most one create/update/status call every 5 seconds
import time
_last = {}
def smart_plus_call(ad_id, fn, *a, **kw):
    wait = 5 - (time.monotonic() - _last.get(ad_id, 0))
    if wait > 0:
        time.sleep(wait)
    try:
        return fn(*a, **kw)
    finally:
        _last[ad_id] = time.monotonic()

When things fail

ScenarioWhat happensPipeline response
Timeout on createUnknown whether TikTok created itRetry with the same request_id
40100 / 40016App-level throttleBack off; after a QPM hit pause 5 minutes
40133Advertiser-level throttleSlow down calls for that advertiser
40050Duplicate requestTreat as already done; look the object up
Smart+ concurrency errorSame ad touched within 5 sWait and retry once
Failure scenarios and responses for a TikTok Smart+ pipeline

App-level limits start at Basic: 10 QPS, 600 QPM and 864,000 QPD, and /ad/create/ is capped at 5 QPS on Basic (Rate limits; Return codes).

Prompting Codex

Read AGENTS.md. In tiktok_pipeline/, implement create_smart_plus.py and throttle.py
as specified. Add pytest tests that mock requests and assert: operation_status is
"DISABLE", request_id is a numeric string and is reused on retry, budget is a float.
Do not call the live API. Show the diff when done.

Put the rules (DISABLE only, request_id reuse, back-off codes, no secrets in logs) in AGENTS.md; Codex reads it before every task (AGENTS.md). A full rule file is in our Codex × TikTok end-to-end guide (Chinese).

# AGENTS.md  (repo root) - rules Codex reads before every task
## TikTok ads automation rules
- Only touch advertiser IDs listed in accounts.allowlist (our own / client-authorised,
  assigned in the client's Business Center).
- Read TIKTOK_APP_ID, TIKTOK_APP_SECRET and TIKTOK_ACCESS_TOKEN from env vars.
  Never print, log or commit them, never put them in prompts.
- Create every campaign, ad group and ad with operation_status = "DISABLE".
  Never send "ENABLE". A media buyer turns delivery on in Ads Manager.
- Generate request_id once per create call (string of a 64-bit int) and reuse it
  on retries so TikTok de-duplicates.
- Budgets are floats in account currency. Never raise a budget >20% in one change.
- Respect rate limits: on code 40100/40016 back off; after a QPM hit wait 5 minutes.
- Upgraded Smart+ ads: max one create/update/status call per ad every 5 seconds.
- Do not build new non-Search Legacy Manual campaigns (unsupported from 2027-01-01).
- Run `pytest -q` and `python -m scripts.dry_run` before proposing changes.
- Flag finance, health, gambling/games, dating and AIGC creatives for human policy review.

Plan for 1 January 2027

TikTok says the legacy create endpoints will stop creating non-Search Legacy Manual campaigns for Sales, App Promotion and Lead Generation from 1 January 2027. Building on Smart+ now avoids a rewrite; migration steps are in our migration guide (Traditional Chinese).

How PandaWM uses Claude, Codex and TikTok 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 TikTok ad accounts to help companies going global move faster through the repetitive loop of account and pixel/event setup → Smart+ campaign builds → creative upload and pre-review → reports and diagnosis → budget and rule changes, so media buyers spend their time on creative strategy, bidding judgement and scaling.

  • Ad accounts: the client’s own TikTok ad account opened under its real business entity; accounts that need industry entry approval (games, finance and similar) go through TikTok’s industry entry process; accounts can also be opened through an authorised agency. Every account belongs to the client, is never rented or shared, and is managed in the client’s own Business Center.
  • Claude: natural-language reporting, TikTok’s official diagnosis agent, creative organisation and Smart+ build plans through the official TikTok for Business MCP Server, with every write tool confirmed before it runs.
  • Codex: Python scripts on Marketing API v1.3 (report pulls, rate-limit retries, Smart+ builds created as DISABLE with idempotent request_id) that run in a sandbox or on a schedule.
  • Human sign-off: a media buyer approves turning delivery on, budget increases and bid changes, and a person makes the final call on TikTok advertising policy for creatives and landing pages.

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

FAQ

Why not let the agent call the API directly?

You can, through the MCP server. Scripts are better for repeatable, reviewed, high-volume builds.

Is the budget in cents?

No. TikTok budgets are floats in the account currency.

Where should the token live?

In a secret manager or environment variable, never in code, prompts or logs.

Can Codex run in mainland China or Hong Kong?

OpenAI does not support them; see OpenAI’s supported countries list in the sources and How to get an OpenAI API key.

Compliance note: Use every workflow in this guide only on TikTok ad accounts (including accounts assigned to you in a Business Center) that your company owns or is formally authorised to manage, through TikTok’s official TikTok API for Business, the TikTok for Business MCP Server or TikTok Ads Manager. Follow TikTok’s advertising policies, industry entry requirements and API rate limits, and keep a human review step before anything that can spend money. PandaWM does not sell, rent, share or transfer ad accounts, Business Centers or API credentials, does not help anyone bypass ad review, industry entry, regional restrictions or identity verification, and is not an official partner of TikTok, Anthropic or OpenAI. Claude and OpenAI services are only offered 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: TikTok Ads accounts + AI-assisted delivery

Tell us where your company is registered, your industry (and whether it needs industry entry approval), target countries, landing page, app or TikTok Shop, and expected monthly budget, plus which part you want to automate first (reporting, creatives, Smart+ builds or rules). We pre-check eligibility and creatives, help you open your own TikTok ad account compliantly, and wire Claude / Codex into your workflow.

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-tiktok-marketing-api-python-smart-plus-pipeline-en.html
上一篇
下一篇

作者: 熊猫出海编辑团队

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

为您推荐

发表回复

联系我们

联系我们

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

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

微信扫一扫关注我们

关注微博
返回顶部