Python 与 Node.js 中的 Instagram API:实用示例
Instagram API 只需要 HTTPS,因此 Python 的 requests 与 Node.js 内置的 fetch 即可胜任:POST /<IG_ID>/media 后调用 media_publish 发布,/<IG_MEDIA_ID>/comments 与 /<IG_COMMENT_ID>/replies 用于读取和回复评论,/insights 返回指标,而 Webhook 则通过原始请求体的 HMAC-SHA256 进行校验。每个错误都带有 code 与 subcode,决定重试是否有帮助。
easyCoexistence 将同样的任务以 MCP 工具的形式提供给 Claude、ChatGPT 或你自己的智能体,令牌由其在自己一侧保管:publish_instagram_post、reply_to_comment、get_social_insights 与 set_social_webhook_destination,基于 Meta 官方 API。
最新的 Graph API 版本于 2026 年 7 月 29 日推出,v25.0 仍可使用至 2028 年 7 月 29 日。
Meta 建议检查视频容器 status_code 的频率,检查时长不超过 5 分钟。
一次 GET /<IG_MEDIA_ID>/comments 请求最多返回的评论数量;回复只能通过字段展开返回。
临时性发布错误,Meta 建议在 30 秒至 2 分钟内重试 1 到 2 次。
X-Hub-Signature-256 中位于 HMAC-SHA256 负载签名之前的前缀,该签名以应用密钥计算。
示例需要什么?
一个运行环境、一个访问令牌和四个值。示例通过 graph.instagram.com 上的 Instagram Login 调用 Instagram API;统一登录应用使用相同的路径,但需带上账户 ID,并使用 Facebook Login 的 Graph 主机及其 Business Integration System User 访问令牌。Python 需要 requests 包,Webhook 还需要 Flask;Node.js 需要 18 或更高版本,以使用其内置的 fetch。
- GRAPH:https://graph.instagram.com/v26.0,即主机与 API 版本。
IG_ID:专业账户的 ID,即 GET /me 返回的user_id。- TOKEN:长期有效的 Instagram 用户访问令牌,须保存在服务器端。
APP_SECRET与VERIFY_TOKEN:用于校验 Webhook 请求。
Python 中如何调用 API 并处理错误?
通过一个辅助函数完成,下面的 Python 示例共用该函数。它将令牌作为 access_token 发送,抛出包含 Meta 的 code、subcode 与 fbtrace_id 的 MetaError,并且只对 Meta 所称的临时性错误进行重试:代码 1 和 2、限流代码 4、17 和 80002,以及子代码 2207001、2207003、2207008 和 2207032。代码 4 搭配子代码 2207051 表示疑似垃圾信息,因此会立即停止。
import json
import time
import requests
GRAPH = "https://graph.instagram.com/v26.0"
IG_ID = "<IG_ID>" # user_id from GET /me
TOKEN = "<TOKEN>" # long-lived Instagram User access token, server side only
RETRY_CODES = {1, 2, 4, 17, 80002}
RETRY_SUBCODES = {2207001, 2207003, 2207008, 2207032}
class MetaError(Exception):
def __init__(self, error: dict, status: int):
super().__init__(error.get("message", f"HTTP {status}"))
self.code = error.get("code")
self.subcode = error.get("error_subcode")
self.fbtrace_id = error.get("fbtrace_id") # log it: Meta support asks for it
@property
def needs_new_token(self) -> bool:
return self.code in (102, 190)
@property
def retryable(self) -> bool:
if self.subcode == 2207051: # code 4 with this subcode is suspected spam: stop
return False
return self.code in RETRY_CODES or self.subcode in RETRY_SUBCODES
def wait_seconds(resp) -> int:
"""estimated_time_to_regain_access from X-Business-Use-Case-Usage, at least 60 s."""
try:
usage = json.loads(resp.headers.get("X-Business-Use-Case-Usage", "{}"))
minutes = max(e.get("estimated_time_to_regain_access", 0) for v in usage.values() for e in v)
except (ValueError, AttributeError, TypeError):
minutes = 0
return max(60, int(minutes) * 60)
def graph(method: str, path: str, attempts: int = 3, **params) -> dict:
if attempts < 1:
raise ValueError("attempts must be at least 1")
params["access_token"] = TOKEN
for attempt in range(1, attempts + 1):
resp = requests.request(method, f"{GRAPH}/{path}", params=params, timeout=30)
try:
data = resp.json()
except ValueError:
data = {}
if resp.ok and "error" not in data:
return data
err = MetaError(data.get("error", {}), resp.status_code)
if not err.retryable or attempt == attempts:
raise err
time.sleep(wait_seconds(resp))Node.js 中如何调用 API 并处理错误?
使用同一个辅助函数(适用于 Node.js 18 或更高版本),基于 fetch,无需任何依赖。受到限流的调用会等待 estimated_time_to_regain_access,即 X-Business-Use-Case-Usage 响应头中 Meta 报告的分钟数;若响应头缺失,则等待 60 秒,因为 Meta 会计入限流期间发出的调用。needsNewToken 会标记代码 190 和 102,这两个错误任何重试都无法解决。
const GRAPH = "https://graph.instagram.com/v26.0";
const IG_ID = process.env.IG_ID; // user_id from GET /me
const TOKEN = process.env.TOKEN; // long-lived Instagram User access token, server side only
const RETRY_CODES = new Set([1, 2, 4, 17, 80002]);
const RETRY_SUBCODES = new Set([2207001, 2207003, 2207008, 2207032]);
export class MetaError extends Error {
constructor(error, status) {
super(error.message ?? `HTTP ${status}`);
this.code = error.code;
this.subcode = error.error_subcode;
this.fbtraceId = error.fbtrace_id; // log it: Meta support asks for it
}
get needsNewToken() {
return this.code === 190 || this.code === 102;
}
get retryable() {
if (this.subcode === 2207051) return false; // code 4 with this subcode is suspected spam: stop
return RETRY_CODES.has(this.code) || RETRY_SUBCODES.has(this.subcode);
}
}
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// estimated_time_to_regain_access from X-Business-Use-Case-Usage, at least 60 s
function waitMs(res) {
try {
const usage = JSON.parse(res.headers.get("x-business-use-case-usage") ?? "{}");
const minutes = Math.max(0, ...Object.values(usage).flat().map((e) => e.estimated_time_to_regain_access ?? 0));
return Math.max(60, minutes * 60) * 1000;
} catch {
return 60_000;
}
}
export async function graph(method, path, params = {}, attempts = 3) {
const url = new URL(`${GRAPH}/${path}`);
for (const [key, value] of Object.entries({ ...params, access_token: TOKEN })) {
url.searchParams.set(key, String(value));
}
for (let attempt = 1; attempt <= attempts; attempt++) {
const res = await fetch(url, { method });
const data = await res.json().catch(() => ({}));
if (res.ok && !data.error) return data;
const err = new MetaError(data.error ?? {}, res.status);
if (!err.retryable || attempt === attempts) throw err;
await sleep(waitMs(res));
}
throw new Error("attempts must be at least 1");
}Python 中如何发布图片和 Reel?
两者都遵循容器流程。图片容器可立即使用,因此 media_publish 紧随其后调用。Reel 的视频需先处理:函数按 Meta 的建议每分钟检查一次 status_code,最多检查 5 分钟,状态为 FINISHED 时发布,为 ERROR 或 EXPIRED 时停止。图片必须为 JPEG,媒体须位于公开 URL 上。
# Uses graph(), IG_ID and time from the helper above
def publish_photo(image_url: str, caption: str) -> str:
"""A JPEG at a public URL: create the container, then publish it."""
container = graph("POST", f"{IG_ID}/media", image_url=image_url, caption=caption)
return graph("POST", f"{IG_ID}/media_publish", creation_id=container["id"])["id"]
def publish_reel(video_url: str, caption: str) -> str:
"""A Reel: publish once Meta has processed the video, checking once a minute."""
cid = graph("POST", f"{IG_ID}/media", media_type="REELS", video_url=video_url, caption=caption)["id"]
for _ in range(5): # Meta: once a minute, for no more than 5 minutes
time.sleep(60)
status = graph("GET", cid, fields="status_code")["status_code"]
if status == "FINISHED":
return graph("POST", f"{IG_ID}/media_publish", creation_id=cid)["id"]
if status in ("ERROR", "EXPIRED"):
raise RuntimeError(f"Container {cid} ended as {status}")
raise TimeoutError(f"Container {cid} is still processing: check it again later")Node.js 中如何发布图片和 Reel?
使用同样的两个函数,每个都返回新媒体 ID。若容器在五次检查后仍为 IN_PROGRESS,其有效期可延续至创建后 24 小时,因此错误提示会建议稍后再次检查,以免额外占用账户每日 400 个容器的配额。
// Uses graph(), sleep() and IG_ID from the helper above
export async function publishPhoto(imageUrl, caption) {
const { id } = await graph("POST", `${IG_ID}/media`, { image_url: imageUrl, caption });
return (await graph("POST", `${IG_ID}/media_publish`, { creation_id: id })).id;
}
export async function publishReel(videoUrl, caption) {
const { id } = await graph("POST", `${IG_ID}/media`, { media_type: "REELS", video_url: videoUrl, caption });
for (let check = 0; check < 5; check++) {
await sleep(60_000); // Meta: once a minute, for no more than 5 minutes
const { status_code: status } = await graph("GET", id, { fields: "status_code" });
if (status === "FINISHED") return (await graph("POST", `${IG_ID}/media_publish`, { creation_id: id })).id;
if (status === "ERROR" || status === "EXPIRED") throw new Error(`Container ${id} ended as ${status}`);
}
throw new Error(`Container ${id} is still processing: check it again later`);
}Python 中如何读取评论并回复?
GET /<IG_MEDIA_ID>/comments 返回顶层评论,按最新排序,每次请求最多 50 条;POST /<IG_COMMENT_ID>/replies 则会公开回复其中某条评论。函数会调用你提供的回调函数,逐条获取回复文本,若某条评论未返回文本则跳过该评论。隐藏的评论无法回复,对回复的回复会落在顶层评论上。
# Uses graph() from the helper above
def reply_to_comments(media_id: str, write_reply) -> int:
"""Reply in public to each comment write_reply returns text for."""
page = graph("GET", f"{media_id}/comments", fields="id,text,username,timestamp")
sent = 0
for comment in page.get("data", []):
text = write_reply(comment)
if text:
graph("POST", f"{comment['id']}/replies", message=text)
sent += 1
return sent
# Example: reply to questions about price
reply_to_comments("<IG_MEDIA_ID>", lambda c: "Prices are in our bio link." if "price" in c["text"].lower() else None)Node.js 中如何读取评论并回复?
与 Node.js 中的循环相同。两个调用都需要 instagram_business_basic 与 instagram_business_manage_comments 权限,其中 username 字段需要后一项权限。若要改为私信回复,可使用 POST /<IG_ID>/messages 并传入 recipient.comment_id,向评论者发送一条私信,该操作须在评论发出后 7 天内完成;若对方尚未回复,后续消息需等待其回应后再发送。
// Uses graph() from the helper above
// Reply in public to each comment writeReply returns text for
export async function replyToComments(mediaId, writeReply) {
const { data = [] } = await graph("GET", `${mediaId}/comments`, { fields: "id,text,username,timestamp" });
let sent = 0;
for (const comment of data) {
const text = writeReply(comment);
if (text) {
await graph("POST", `${comment.id}/replies`, { message: text });
sent++;
}
}
return sent;
}
// Example: reply to questions about price
await replyToComments("<IG_MEDIA_ID>", (c) => (/price/i.test(c.text) ? "Prices are in our bio link." : null));Python 中如何读取数据洞察?
账户洞察使用 period=day 与 metric_type=total_value,随后每个指标返回 total_value.value;帖子的洞察返回 values[0].value。示例在账户上请求 reach、views 和 accounts_engaged,在帖子或 Reel 上请求 reach、views、likes、comments、saved 和 shares,这些指标在 Meta 参考文档中两者均有列出。没有数据的指标会被省略,而不是返回 0。
# Uses graph() and IG_ID from the helper above
def account_insights() -> dict:
"""Reach, views and accounts engaged over the last 24 hours."""
data = graph("GET", f"{IG_ID}/insights", metric="reach,views,accounts_engaged",
period="day", metric_type="total_value")["data"]
return {m["name"]: m["total_value"]["value"] for m in data}
def post_insights(media_id: str) -> dict:
"""Totals for one post or Reel."""
data = graph("GET", f"{media_id}/insights", metric="reach,views,likes,comments,saved,shares")["data"]
return {m["name"]: m["values"][0]["value"] for m in data}Node.js 中如何读取数据洞察?
在 Node.js 中发出同样的两个请求,每个都返回以指标名为键的对象。两者均不发送 breakdown 参数:Meta 警告,若请求某指标不支持的 breakdown,会以未知错误使请求失败;而且洞察数据可能滞后最多 48 小时,因此应稍后再次读取近期帖子。
// Uses graph() and IG_ID from the helper above
// Reach, views and accounts engaged over the last 24 hours
export async function accountInsights() {
const { data } = await graph("GET", `${IG_ID}/insights`, {
metric: "reach,views,accounts_engaged",
period: "day",
metric_type: "total_value",
});
return Object.fromEntries(data.map((m) => [m.name, m.total_value?.value]));
}
// Totals for one post or Reel
export async function postInsights(mediaId) {
const { data } = await graph("GET", `${mediaId}/insights`, { metric: "reach,views,likes,comments,saved,shares" });
return Object.fromEntries(data.map((m) => [m.name, m.values?.[0]?.value]));
}Python 中如何验证 Webhook?
使用 Flask,在同一路径上的两个路由中完成。GET 用于响应 Meta 的验证请求:当 hub.mode 为 subscribe 且 hub.verify_token 匹配时,以纯文本返回 hub.challenge,否则返回 403。POST 使用应用密钥计算原始请求体的 HMAC-SHA256 并加上 sha256= 前缀,以恒定时间与 X-Hub-Signature-256 比较,并在任何耗时操作开始前返回 200。
import hashlib
import hmac
import json
import os
from queue import Queue
from flask import Flask, abort, request
app = Flask(__name__)
VERIFY_TOKEN = os.environ["VERIFY_TOKEN"]
APP_SECRET = os.environ["APP_SECRET"].encode()
jobs: Queue = Queue() # swap for your own job queue
@app.get("/webhooks/instagram")
def verify():
"""Meta's verification request: send hub.challenge back when the token matches."""
args = request.args
if args.get("hub.mode") == "subscribe" and args.get("hub.verify_token") == VERIFY_TOKEN:
return args.get("hub.challenge", ""), 200, {"Content-Type": "text/plain"}
abort(403)
@app.post("/webhooks/instagram")
def receive():
"""An event: check X-Hub-Signature-256 over the raw bytes, then answer at once."""
raw = request.get_data()
expected = b"sha256=" + hmac.new(APP_SECRET, raw, hashlib.sha256).hexdigest().encode()
if not hmac.compare_digest(expected, request.headers.get("X-Hub-Signature-256", "").encode()):
abort(401)
for entry in json.loads(raw).get("entry", []):
jobs.put(entry) # slow work happens elsewhere; Meta wants a quick 200
return "", 200Node.js 中如何验证 Webhook?
使用内置的 http 模块,不依赖任何框架。在解析之前,请求体先以原始字节收集,因为解析后再重新序列化的请求体,将无法与 Meta 计算的签名匹配。Meta 最多会对失败的通知重试 36 小时,因此处理程序还应跳过已处理过的事件。
import crypto from "node:crypto";
import http from "node:http";
const { VERIFY_TOKEN, APP_SECRET } = process.env;
const PATH = "/webhooks/instagram";
const jobs = []; // swap for your own job queue
http
.createServer((req, res) => {
const url = new URL(req.url, "http://localhost");
if (url.pathname !== PATH) return res.writeHead(404).end();
if (req.method === "GET") {
// Meta's verification request: send hub.challenge back when the token matches
const ok =
url.searchParams.get("hub.mode") === "subscribe" &&
url.searchParams.get("hub.verify_token") === VERIFY_TOKEN;
return res
.writeHead(ok ? 200 : 403, { "Content-Type": "text/plain" })
.end(ok ? url.searchParams.get("hub.challenge") ?? "" : "");
}
const chunks = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => {
const raw = Buffer.concat(chunks); // the exact bytes Meta signed
const expected = Buffer.from("sha256=" + crypto.createHmac("sha256", APP_SECRET).update(raw).digest("hex"));
const given = Buffer.from(req.headers["x-hub-signature-256"] ?? "");
if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
return res.writeHead(401).end();
}
res.writeHead(200).end(); // answer first, work after
try {
for (const entry of JSON.parse(raw.toString("utf8")).entry ?? []) jobs.push(entry);
} catch {
// not JSON: nothing to queue
}
});
})
.listen(3000);代码应该重试哪些 Meta 错误?
只重试临时性错误,因为其余错误在文件、URL、权限或账户状态发生变化之前,会一直返回相同的结果。以下是 Meta 错误参考文档中,针对上述辅助函数所区分的各个代码及其对应操作:
如何在 easyCoexistence 的凭据上运行同样的代码?
无法在 easyCoexistence 的令牌上运行:Instagram 令牌从不对外交付(Meta 条款),因此 get_social_credentials 和 Partner API 的 GET /api/v1/channels/:id?credentials=1 只返回账户的 ID 和 API 基础地址,不含令牌。同样的任务可改为以 MCP 工具的形式运行,通过 Claude、ChatGPT 或其他 MCP 客户端调用;上面的辅助函数则可在您自己 Meta 应用的令牌上无需修改地运行。
{
"platform": "instagram",
"graph_api_base": "https://graph.instagram.com/<VERSION>",
"account_id_on_meta": "<IG_ID>",
"access_token": null,
"token_note": "Meta's terms do not allow handing this account's access token to other apps, so it is not shown. ..."
}如何通过 MCP 连接器完成同样的任务?
可以直接向助手提出请求,也可以自行调用这些工具。publish_instagram_post 会创建并发布容器,在视频处理期间等待;或者通过 scheduled_at 定时发布,最长可提前 90 天。reply_to_comment 用于公开回复,若将 private 设为 true 则改为私信回复;get_social_insights 将指标名称直接传给 Meta;set_social_webhook_destination 将评论、提及和私信转发至你的端点,并使用 X-EC-Signature 签名。
[
{
"name": "publish_instagram_post",
"arguments": {
"account_id": "<from list_social_accounts>",
"type": "REELS",
"video_url": "https://cdn.example.com/launch.mp4",
"caption": "Launch day.",
"scheduled_at": "2026-11-06T09:00:00-03:00"
}
},
{
"name": "list_social_comments",
"arguments": { "account_id": "<ACCOUNT_ID>", "post_id": "<IG_MEDIA_ID>" }
},
{
"name": "reply_to_comment",
"arguments": { "account_id": "<ACCOUNT_ID>", "comment_id": "<IG_COMMENT_ID>", "text": "Prices are in our bio link." }
},
{
"name": "get_social_insights",
"arguments": {
"account_id": "<ACCOUNT_ID>",
"metrics": ["reach", "views", "accounts_engaged"],
"period": "day",
"params": { "metric_type": "total_value" }
}
},
{
"name": "set_social_webhook_destination",
"arguments": { "account_id": "<ACCOUNT_ID>", "url": "https://hooks.example.com/instagram" }
}
]常见错误
- 对解析后的 JSON 进行哈希。Meta 对原始字节签名,因此框架的 JSON 请求体解析器会使 X-Hub-Signature-256 校验失败;应保留原始请求体,之后再解析。
- 超时后未检查就再次调用 media_publish。如果容器的 status_code 显示 PUBLISHED,则帖子已经上线。
- 把代码 4 当作限流而忽略子代码。搭配 2207051 时,表示 Instagram 怀疑存在垃圾信息,此时重试会重复刚被限制的操作。
- 从浏览器或移动端代码发送应用密钥或访问令牌。Meta 表示,携带应用密钥的请求只应放在服务器端代码中。
每个连接每月 US$ 9 起,随连接数增加最低降至 US$ 0.75,前 3 天免费。
常见问题
调用 Instagram API 需要 SDK 吗?
不需要。每次调用都是带访问令牌的 HTTPS 请求,因此本页示例中的 Python requests 或 Node.js fetch 即可满足需求。
Reel 容器刚创建后,为什么 media_publish 会失败?
视频仍在处理中,会返回错误 9007,子代码为 2207027。请每分钟检查一次容器的 status_code,待其显示 FINISHED 后再发布。
代码应使用哪个 API 版本?
使用 Meta 仍然提供服务的版本:v26.0 为最新版本,每个版本至少可使用两年。对已移除版本的调用会转到仍可用的下一个最旧版本。
easyCoexistence 为 Instagram 账户的 API 访问收费多少?
每个 Instagram 账户算作一个连接:每个连接每月 US$ 9 起,随连接数增加最低降至 US$ 0.75,前 3 天免费。
继续阅读
两分钟连接您的第一个渠道。
无需等待平台审核。连接 WhatsApp、Instagram、TikTok 或其他渠道,然后让您的 AI 发布、回复或生成报告,看它如何运作。
- 免费试用 3 天
- 随时取消
- 仅使用官方 API
- 全天候 24/7 监控
验证时间