TikTok API in Python and Node.js: working examples
TikTok's API for Business works from Python or Node.js with plain HTTPS requests: send each call to https://business-api.tiktok.com/open_api/v1.3 with the account's token in the Access-Token header and its open_id as business_id. TikTok answers most calls with HTTP 200 and a code field, 0 on success, so check it and pause 5 minutes on 40100.
easyCoexistence gives Claude, ChatGPT or your own code the same TikTok jobs as tools, from publish_tiktok_post and reply_to_comment to get_social_insights, and hands your scripts a current token through get_social_credentials or the Partner API.
Status of most TikTok answers, errors included; only a code of 0 in the body means the call worked.
Code for a throttled call: TikTok asks for a 5-minute pause after a per-minute limit, and 00:00 UTC after a daily one.
Server errors, after which TikTok suggests waiting about 5 minutes before calling again.
Paths end in a slash; TikTok gives /tt_user/oauth2/refresh_token without it as a cause of 404 page not found.
Python, JavaScript and Java in TikTok's API for Business SDK, whose endpoint list includes no /business/ endpoint.
Signature in each webhook's Tiktok-Signature header, over the timestamp, a dot and the body, keyed with the app secret.
What does each TikTok API call need?
The same five things, whatever the job:
- The base URL https://business-api.tiktok.com/
open_api/v1.3, with a path that ends in a slash, such as /business/video/list/. - The account's access token in an Access-Token header, renewed before its 24 hours run out.
business_id, the account'sopen_id: in the query string on GET, in the JSON body on POST.- List and object parameters on GET, such as fields and filters, sent as JSON text: fields=["
item_id","caption"]. - A check of code in the answer, since TikTok sends errors such as 40002 or 40100 with HTTP 200 and data only when code is 0.
How do you handle TikTok's error envelope in Python?
With a small client that puts business_id where each method expects it, returns data when code is 0 and raises a TikTokError otherwise. It repeats a throttled call after TikTok's 5-minute pause, since 40100 means TikTok refused the call, and repeats a 5xx only on GET, because a publish that ended in a server error may still have reached TikTok. It needs requests, and the later Python examples reuse it:
import json
import os
import time
import requests
API = "https://business-api.tiktok.com/open_api/v1.3"
class TikTokError(Exception):
def __init__(self, code, message, request_id):
super().__init__(f"TikTok {code}: {message} (request_id {request_id})")
self.code = code
class TikTok:
"""One TikTok account: its access token and its business_id, the open_id."""
def __init__(self, access_token, business_id, pause=300):
self.http = requests.Session()
self.http.headers["Access-Token"] = access_token
self.business_id = business_id
self.pause = pause # TikTok's advice after a 40100 or a 5xx: about 5 minutes
def call(self, method, path, params=None, body=None, tries=3):
for attempt in range(1, tries + 1):
if method == "GET":
query = {"business_id": self.business_id}
for key, value in (params or {}).items():
is_json = isinstance(value, (list, dict))
query[key] = json.dumps(value, separators=(",", ":")) if is_json else value
res = self.http.get(f"{API}/{path}", params=query, timeout=30)
else:
payload = {"business_id": self.business_id, **(body or {})}
res = self.http.post(f"{API}/{path}", json=payload, timeout=30)
if res.status_code >= 500 and method == "GET" and attempt < tries:
time.sleep(self.pause) # a POST is not repeated: it may have reached TikTok
continue
res.raise_for_status() # a 4xx: a wrong path or method, such as a missing final slash
answer = res.json()
if answer.get("code") == 0:
return answer.get("data") or {}
if answer.get("code") == 40100 and attempt < tries:
time.sleep(self.pause) # throttled: TikTok refused the call, so repeating it is safe
continue
raise TikTokError(answer.get("code"), answer.get("message"), answer.get("request_id"))
tt = TikTok(os.environ["TIKTOK_ACCESS_TOKEN"], os.environ["TIKTOK_BUSINESS_ID"])How do you handle it in Node.js?
The same client on the fetch built into Node.js 18 and later, with nothing to install. It encodes list parameters as JSON for GET, puts business_id in the body for POST, and keeps TikTok's code on the error, so callers can tell 40102 or 40105, a token problem, from 40001, a missing permission:
const API = "https://business-api.tiktok.com/open_api/v1.3";
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
class TikTokError extends Error {
constructor(code, message, requestId) {
super("TikTok " + code + ": " + message + " (request_id " + requestId + ")");
this.code = code;
}
}
// One TikTok account: its access token and its business_id, the open_id.
class TikTok {
constructor(accessToken, businessId, pauseMs = 300000) {
this.accessToken = accessToken;
this.businessId = businessId;
this.pauseMs = pauseMs; // TikTok's advice after a 40100 or a 5xx: about 5 minutes
}
async call(method, path, { params = {}, body = {} } = {}, tries = 3) {
for (let attempt = 1; ; attempt++) {
const url = new URL(API + "/" + path);
const init = { method, headers: { "Access-Token": this.accessToken } };
if (method === "GET") {
url.searchParams.set("business_id", this.businessId);
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
}
} else {
init.headers["Content-Type"] = "application/json";
init.body = JSON.stringify({ business_id: this.businessId, ...body });
}
const res = await fetch(url, init);
if (res.status >= 500 && method === "GET" && attempt < tries) {
await sleep(this.pauseMs); // a POST is not repeated: it may have reached TikTok
continue;
}
if (!res.ok) throw new Error("HTTP " + res.status + " on " + path + ": check the path, its final slash and the method");
const answer = await res.json();
if (answer.code === 0) return answer.data ?? {};
if (answer.code === 40100 && attempt < tries) {
await sleep(this.pauseMs); // throttled: TikTok refused the call, so repeating it is safe
continue;
}
throw new TikTokError(answer.code, answer.message, answer.request_id);
}
}
}
const tt = new TikTok(process.env.TIKTOK_ACCESS_TOKEN, process.env.TIKTOK_BUSINESS_ID);How do you publish a video by URL and check its status?
POST /business/video/publish/ with video_url and post_info, then poll /business/publish/status/ with the share_id as publish_id. The loop stops on FAILED with TikTok's reason, and on PUBLISH_COMPLETE it keeps waiting until post_ids arrives, which TikTok says can take up to three more minutes. The video_url has to sit on a domain or URL prefix verified for your app:
# Python
def wait_until_live(tt, share_id, interval=30, give_up_after=7200):
deadline = time.time() + give_up_after
while time.time() < deadline:
status = tt.call("GET", "business/publish/status/", params={"publish_id": share_id})
if status["status"] == "FAILED":
raise RuntimeError(f"TikTok did not publish {share_id}: {status.get('reason')}")
if status["status"] == "PUBLISH_COMPLETE" and status.get("post_ids"):
return status["post_ids"]
time.sleep(interval) # post_ids can follow PUBLISH_COMPLETE by up to three minutes
raise TimeoutError(f"{share_id} was not public after {give_up_after} s")
video = tt.call("POST", "business/video/publish/", body={
"video_url": "https://media.example.com/tiktok/launch.mp4", # on a verified domain or URL prefix
"post_info": {
"caption": "Our spring menu is live #food",
"is_brand_organic": True, # the Promotional content label, for the account's own business
"is_branded_content": False,
},
})
print("Live:", wait_until_live(tt, video["share_id"]))
// Node.js
async function waitUntilLive(tt, shareId, everyMs = 30000, giveUpAfterMs = 7200000) {
const deadline = Date.now() + giveUpAfterMs;
while (Date.now() < deadline) {
const s = await tt.call("GET", "business/publish/status/", { params: { publish_id: shareId } });
if (s.status === "FAILED") throw new Error("TikTok did not publish " + shareId + ": " + s.reason);
if (s.status === "PUBLISH_COMPLETE" && s.post_ids && s.post_ids.length) return s.post_ids;
await sleep(everyMs); // post_ids can follow PUBLISH_COMPLETE by up to three minutes
}
throw new Error(shareId + " was not public after " + giveUpAfterMs / 1000 + " s");
}
async function publishVideo(tt) {
const video = await tt.call("POST", "business/video/publish/", {
body: {
video_url: "https://media.example.com/tiktok/launch.mp4", // on a verified domain or URL prefix
post_info: { caption: "Our spring menu is live #food", is_brand_organic: true, is_branded_content: false },
},
});
return waitUntilLive(tt, video.share_id);
}
publishVideo(tt).then((postIds) => console.log("Live:", postIds), console.error);How do you post photos?
Read the account's allowed settings first, then POST /business/photo/publish/. A photo post requires privacy_level, which has to be one of the privacy_level_options from /business/video/settings/, and when comment_disabled is true there, disable_comment has to be true as well. The returned share_id is followed with the same wait function as a video:
# Python
def publish_photos(tt, image_urls, title, caption):
settings = tt.call("GET", "business/video/settings/")
if "PUBLIC_TO_EVERYONE" not in settings["privacy_level_options"]:
raise RuntimeError(f"Private account, choose from {settings['privacy_level_options']}")
photo = tt.call("POST", "business/photo/publish/", body={
"photo_images": image_urls, # 1 to 35 JPG, JPEG or WebP links on a verified domain or prefix
"photo_cover_index": 0,
"post_info": {
"title": title, # up to 90 UTF-16 code units
"caption": caption, # up to 4,000
"privacy_level": "PUBLIC_TO_EVERYONE",
"disable_comment": settings["comment_disabled"], # True when the account takes no comments
"is_brand_organic": True,
"is_branded_content": False,
},
})
return wait_until_live(tt, photo["share_id"])
print(publish_photos(tt, ["https://media.example.com/menu/1.jpg", "https://media.example.com/menu/2.jpg"],
"Spring menu", "Four new dishes, from Friday #food"))
// Node.js
async function publishPhotos(tt, imageUrls, title, caption) {
const settings = await tt.call("GET", "business/video/settings/");
if (!settings.privacy_level_options.includes("PUBLIC_TO_EVERYONE")) {
throw new Error("Private account, choose from " + settings.privacy_level_options.join(", "));
}
const photo = await tt.call("POST", "business/photo/publish/", {
body: {
photo_images: imageUrls, // 1 to 35 JPG, JPEG or WebP links on a verified domain or prefix
photo_cover_index: 0,
post_info: {
title, // up to 90 UTF-16 code units
caption, // up to 4,000
privacy_level: "PUBLIC_TO_EVERYONE",
disable_comment: settings.comment_disabled, // true when the account takes no comments
is_brand_organic: true,
is_branded_content: false,
},
},
});
return waitUntilLive(tt, photo.share_id);
}
publishPhotos(tt, ["https://media.example.com/menu/1.jpg", "https://media.example.com/menu/2.jpg"],
"Spring menu", "Four new dishes, from Friday #food").then(console.log, console.error);How do you list an account's videos?
GET /business/video/list/ with the fields you want, item_id among them, up to 20 posts a page from the newest. Pass the returned cursor, a UTC timestamp in milliseconds, while has_more is true, and expect short pages: TikTok's trust and safety rules can return fewer than max_count before the list ends.
# Python
def recent_videos(tt, how_many=60):
params = {"fields": ["item_id", "create_time", "caption", "share_url", "video_views", "likes", "comments"],
"max_count": 20}
videos = []
while len(videos) < how_many:
page = tt.call("GET", "business/video/list/", params=params)
videos += page.get("videos", [])
if not page.get("has_more"):
break
params["cursor"] = page["cursor"] # posts published before this UTC time, in milliseconds
return videos[:how_many]
for v in recent_videos(tt):
print(v["item_id"], v.get("video_views"), (v.get("caption") or "")[:60])
// Node.js
async function recentVideos(tt, howMany = 60) {
const params = {
fields: ["item_id", "create_time", "caption", "share_url", "video_views", "likes", "comments"],
max_count: 20,
};
const videos = [];
while (videos.length < howMany) {
const page = await tt.call("GET", "business/video/list/", { params });
videos.push(...(page.videos ?? []));
if (!page.has_more) break;
params.cursor = page.cursor; // posts published before this UTC time, in milliseconds
}
return videos.slice(0, howMany);
}
recentVideos(tt).then((videos) => {
for (const v of videos) console.log(v.item_id, v.video_views, (v.caption || "").slice(0, 60));
}, console.error);How do you read comments and reply to them?
GET /business/comment/list/ with the post's item_id as video_id returns up to 30 comments a page, and POST /business/comment/reply/create/ replies to one in public with up to 1,200 characters of text. The example replies to top-level public comments that have no replies yet, skips the account's own, and leaves the wording to a function you write, since TikTok can hide largely similar comments posted close together as spam:
# Python
def reply_to_new_comments(tt, video_id, write_reply):
page = tt.call("GET", "business/comment/list/", params={
"video_id": video_id, # the post's item_id
"status": "PUBLIC",
"sort_field": "create_time",
"sort_order": "desc",
"max_count": 30,
})
for comment in page.get("comments", []):
if comment.get("owner") or comment.get("replies") or comment.get("parent_comment_id"):
continue # the account's own comments, threads with replies, and replies
text = write_reply(comment)
if text:
tt.call("POST", "business/comment/reply/create/", body={
"video_id": video_id, "comment_id": comment["comment_id"], "text": text, # up to 1,200 characters
})
def reply_for(comment):
if "price" in (comment.get("text") or "").lower():
return f"Hi {comment.get('display_name') or 'there'}, the price list is pinned on our profile."
return None # leave the rest to a person
reply_to_new_comments(tt, "<ITEM_ID>", reply_for)
// Node.js
async function replyToNewComments(tt, videoId, writeReply) {
const page = await tt.call("GET", "business/comment/list/", {
params: { video_id: videoId, status: "PUBLIC", sort_field: "create_time", sort_order: "desc", max_count: 30 },
});
for (const comment of page.comments ?? []) {
if (comment.owner || comment.replies || comment.parent_comment_id) continue; // own, already replied to, or a reply
const text = writeReply(comment);
if (text) {
await tt.call("POST", "business/comment/reply/create/", {
body: { video_id: videoId, comment_id: comment.comment_id, text }, // up to 1,200 characters
});
}
}
}
function replyFor(comment) {
if ((comment.text || "").toLowerCase().includes("price")) {
return "Hi " + (comment.display_name || "there") + ", the price list is pinned on our profile.";
}
return null; // leave the rest to a person
}
replyToNewComments(tt, "<ITEM_ID>", replyFor).catch(console.error);How do you read account insights?
GET /business/get/ with the field names in fields and a UTC date range of up to 60 days. followers_count comes twice: the current total at the top of data, and the total on each day inside metrics, beside that day's video_views, profile_views, likes, comments and shares. The example ends yesterday, since daily counts arrive 24 to 48 hours late:
# Python
from datetime import datetime, timedelta, timezone
def daily_insights(tt, days=7):
yesterday = datetime.now(timezone.utc).date() - timedelta(days=1) # counts arrive 24 to 48 h late
data = tt.call("GET", "business/get/", params={
"fields": ["followers_count", "video_views", "profile_views", "likes", "comments", "shares"],
"start_date": (yesterday - timedelta(days=days - 1)).isoformat(), # UTC, up to 60 days back
"end_date": yesterday.isoformat(),
})
print("Followers now:", data.get("followers_count"))
for day in data.get("metrics", []):
print(day["date"], day.get("followers_count"), day.get("video_views"), day.get("likes"))
daily_insights(tt)
// Node.js
async function dailyInsights(tt, days = 7) {
const utcDay = (daysAgo) => new Date(Date.now() - daysAgo * 86400000).toISOString().slice(0, 10);
const data = await tt.call("GET", "business/get/", {
params: {
fields: ["followers_count", "video_views", "profile_views", "likes", "comments", "shares"],
start_date: utcDay(days), // UTC, up to 60 days back
end_date: utcDay(1), // counts arrive 24 to 48 h late
},
});
console.log("Followers now:", data.followers_count);
for (const day of data.metrics ?? []) console.log(day.date, day.followers_count, day.video_views, day.likes);
}
dailyInsights(tt).catch(console.error);How do you verify a webhook signature?
Recompute an HMAC-SHA256 of the t value, a dot and the raw body, keyed with the app secret, compare it with s in constant time, and check that t is recent. Read the body as bytes before anything parses it, answer 200 at once, and log x-tt-logid when a check fails. Flask for Python, and the built-in http module for Node.js:
# Python
import hashlib
import hmac
import json
import os
import time
from queue import Queue
from flask import Flask, request
app = Flask(__name__)
events = Queue()
def signature_ok(raw, header, secret, max_age=300):
fields = {}
for part in (header or "").split(","):
key, sep, value = part.strip().partition("=")
if sep:
fields[key] = value
t, s = fields.get("t", ""), fields.get("s", "").lower()
if not t.isdigit() or len(s) != 64:
return False
expected = hmac.new(secret.encode(), t.encode() + b"." + raw, hashlib.sha256).hexdigest()
return hmac.compare_digest(expected, s) and abs(time.time() - int(t)) <= max_age
@app.post("/tiktok/webhook")
def tiktok_webhook():
raw = request.get_data() # the bytes TikTok signed, before any JSON parsing
if not signature_ok(raw, request.headers.get("Tiktok-Signature"), os.environ["TIKTOK_APP_SECRET"]):
app.logger.warning("Bad signature, x-tt-logid %s", request.headers.get("X-Tt-Logid"))
return "", 401
events.put(json.loads(raw)) # its content field is itself a JSON string: work on it elsewhere
return "", 200
// Node.js
const { createServer } = require("node:http");
const { createHmac, timingSafeEqual } = require("node:crypto");
function signatureOk(raw, header, secret, maxAgeSec = 300) {
const fields = {};
for (const part of String(header ?? "").split(",")) {
const i = part.indexOf("=");
if (i > 0) fields[part.slice(0, i).trim()] = part.slice(i + 1).trim();
}
if (!/^\d+$/.test(fields.t ?? "") || !/^[0-9a-f]{64}$/i.test(fields.s ?? "")) return false;
const expected = createHmac("sha256", secret).update(fields.t + ".").update(raw).digest();
const fresh = Math.abs(Date.now() / 1000 - Number(fields.t)) <= maxAgeSec;
return timingSafeEqual(expected, Buffer.from(fields.s, "hex")) && fresh;
}
const inbox = [];
createServer((req, res) => {
if (req.method !== "POST" || req.url !== "/tiktok/webhook") return res.writeHead(404).end();
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const raw = Buffer.concat(chunks); // the bytes TikTok signed
if (!signatureOk(raw, req.headers["tiktok-signature"], process.env.TIKTOK_APP_SECRET)) {
console.warn("Bad signature, x-tt-logid", req.headers["x-tt-logid"]);
return res.writeHead(401).end();
}
res.writeHead(200).end(); // answer first: TikTok retries anything but a 200 for up to 72 hours
inbox.push(JSON.parse(raw.toString("utf8")));
});
}).listen(3000);How do you run the same jobs through easyCoexistence?
As tool calls from Claude, ChatGPT or another MCP client connected to https://easycoexistence.com/api/mcp, each taking the account_id from list_social_accounts. easyCoexistence sends your media links to TikTok through its own verified URL prefix, follows each post until TikTok completes or fails it, and renews the token, while a refused call comes back with TikTok's code and message:
// Publish a video by URL, then see where it stands
publish_tiktok_post { "account_id": "<ACCOUNT_ID>", "video_url": "https://media.example.com/tiktok/launch.mp4", "caption": "Our spring menu is live #food" }
get_tiktok_publish_status { "account_id": "<ACCOUNT_ID>", "share_id": "<SHARE_ID>" }
// Post photos
publish_tiktok_post { "account_id": "<ACCOUNT_ID>", "image_urls": ["https://media.example.com/menu/1.jpg", "https://media.example.com/menu/2.jpg"], "title": "Spring menu", "caption": "Four new dishes, from Friday #food" }
// List videos
list_social_posts { "account_id": "<ACCOUNT_ID>", "limit": 20 }
// Read comments and reply in public
list_social_comments { "account_id": "<ACCOUNT_ID>", "post_id": "<ITEM_ID>" }
reply_to_comment { "account_id": "<ACCOUNT_ID>", "post_id": "<ITEM_ID>", "comment_id": "<COMMENT_ID>", "text": "The price list is pinned on our profile." }
// Account insights
get_social_insights { "account_id": "<ACCOUNT_ID>", "metrics": ["followers_count", "video_views", "likes"], "params": { "start_date": "2026-10-26", "end_date": "2026-11-01" } }
// Comment events, signed by easyCoexistence, at your endpoint
set_social_webhook_destination { "account_id": "<ACCOUNT_ID>", "url": "https://hooks.example.com/tiktok/" }How does your own code use an account connected to easyCoexistence?
Fetch the account's credentials per job from the Partner API and pass them to the same client. GET /channels/{id}?credentials=1 with your ec_live_ key returns api_base, business_id and a current access_token with token_expires_at, or a null token with a note when the channel needs reconnecting. Reads, replies and insights then run from your own code, while posts go through POST /channels/{id}/posts or publish_tiktok_post, which route media through the verified prefix:
# Python
def tiktok_for(channel_id):
res = requests.get(f"https://easycoexistence.com/api/v1/channels/{channel_id}", params={"credentials": "1"},
headers={"Authorization": f"Bearer {os.environ['EC_API_KEY']}"}, timeout=30)
res.raise_for_status()
creds = res.json()["credentials"]
if not creds.get("access_token"):
raise RuntimeError(creds.get("note")) # the channel needs reconnecting
return TikTok(creds["access_token"], creds["business_id"])
print(recent_videos(tiktok_for("<CHANNEL_ID>"), 20))
// Node.js
async function tiktokFor(channelId) {
const res = await fetch("https://easycoexistence.com/api/v1/channels/" + channelId + "?credentials=1", {
headers: { Authorization: "Bearer " + process.env.EC_API_KEY },
});
if (!res.ok) throw new Error("HTTP " + res.status + " from easyCoexistence");
const { credentials } = await res.json();
if (!credentials.access_token) throw new Error(credentials.note); // the channel needs reconnecting
return new TikTok(credentials.access_token, credentials.business_id);
}
tiktokFor("<CHANNEL_ID>").then((account) => recentVideos(account, 20)).then(console.log, console.error);Common mistakes
- Reading data without checking code. An answer can carry HTTP 200, code 40002 and no data at all, so a missing field is often an error the code skipped.
- Dropping the final slash. TikTok's paths end in /, and its return code appendix gives /tt_user/oauth2/refresh_token, without the slash, as a call that ends in HTTP 404 page not found.
- Taking reply IDs from reply_list in Node.js. TikTok's reference types reply_list's comment_id and video_id as numbers, which JSON.parse can round; /business/comment/reply/list/ returns them as strings.
- Sending fields as a comma list. The API for Business wants JSON text, fields=["item_id","caption"], unlike the Display API on developers.tiktok.com, which takes fields=open_id,union_id.
US$ 9 to US$ 0.75 per connection per month, falling as you add connections, with the first 3 days free.
easyCoexistence is a multichannel API and MCP server that connects AI agents such as Claude and ChatGPT to WhatsApp, Instagram, TikTok, Facebook and more. On WhatsApp it uses Coexistence: the business keeps using its number in the WhatsApp Business app while the AI works through Meta's official API.
Frequently asked questions
Does TikTok have an official Python or Node.js SDK for the Accounts API?
TikTok's API for Business SDK comes in Python, JavaScript and Java, but its endpoint list covers ads, reporting and Business Center, with no /business/ or /tt_user/ endpoint.
Why does a TikTok call return HTTP 200 with no data?
TikTok reports errors in the code field of an HTTP 200 answer. Read code and message: 40002 is a parameter error, 40001 a missing permission and 40100 a throttled call.
Which Python and Node.js versions do these examples need?
Python 3.9 or later with requests, plus Flask for the webhook, and Node.js 18 or later, whose built-in fetch and node:crypto cover the rest.
Can I call the TikTok API from the browser?
Keep the calls on your server. TikTok's token type is Bearer, usable by anyone who holds it, and the token endpoints need your app's client_secret.
Keep reading
Connect your first channel in two minutes.
No platform reviews to wait for. Connect WhatsApp, Instagram, TikTok or another channel, then ask your AI to post, reply or report, and watch it work.
- 3 days free
- Cancel any time
- Official APIs only
- Monitored 24/7
Verified on