Instagram API sa Python at Node.js: mga gumaganang halimbawa
Wala nang kailangan ang Instagram API bukod sa HTTPS, kaya sapat na ang requests ng Python at ang built-in na fetch ng Node.js. Ang POST /<IG_ID>/media at media_publish ang nagpa-publish, ang /<IG_MEDIA_ID>/comments at /<IG_COMMENT_ID>/replies ang nagbabasa at sumasagot sa comments, ang /insights ang nagbabalik ng metrics, at ang webhook ay sinusuri gamit ang HMAC-SHA256 ng raw body. Bawat error ay may code at subcode na nagsasabi kung makakatulong ang retry.
Pinapatakbo ng easyCoexistence ang parehong gawain bilang MCP tools para sa Claude, ChatGPT o sarili ninyong agent, na nananatili sa panig nito ang token: publish_instagram_post, reply_to_comment, get_social_insights at set_social_webhook_destination, sa opisyal na API ng Meta.
Ang pinakabagong Graph API version, inilabas noong 29 Hulyo 2026; mananatiling available ang v25.0 hanggang 29 Hulyo 2028.
Gaano kadalas inirerekomendang tingnan ang status_code ng video container, nang hindi lalampas sa 5 minuto.
Pinakamaraming comments na ibinabalik ng isang GET /<IG_MEDIA_ID>/comments request; ang replies ay lumalabas lamang sa pamamagitan ng field expansion.
Pansamantalang publishing error, na ayon sa Meta ay i-retry nang 1 hanggang 2 beses sa loob ng 30 segundo hanggang 2 minuto.
Ang prefix sa X-Hub-Signature-256, bago ang HMAC-SHA256 ng payload na naka-key sa app secret.
Ano ang kailangan ng mga halimbawa?
Runtime, token, at apat na value. Tinatawag ng mga halimbawa ang Instagram API gamit ang Instagram Login sa graph.instagram.com; ang Unified Login app ay gumagamit ng parehong path gamit ang ID ng account, sa Graph host ng Facebook Login kasama ang Business Integration System User token nito. Kailangan ng Python ang requests package, kasama ang Flask para sa webhook, at ang Node.js ay nangangailangan ng bersyon 18 o mas bago para sa built-in nitong fetch.
- GRAPH: https://graph.instagram.com/v26.0, ang host at ang bersyon ng API.
IG_ID: ang ID ng professional account, anguser_idna ibinabalik ng GET /me.- TOKEN: isang long-lived Instagram User access token, itinatago sa server.
APP_SECRETatVERIFY_TOKEN: para sa pag-verify ng mga webhook request.
Paano tumawag sa API at pangasiwaan ang errors sa Python?
Sa pamamagitan ng iisang helper na ibinabahagi ng mga Python na halimbawa sa ibaba. Ipinapadala nito ang token bilang access_token, nagtataas ng MetaError kasama ang code, subcode at fbtrace_id ng Meta, at nagre-retry lamang sa tinatawag ng Meta na pansamantala: ang code 1 at 2, ang throttling codes na 4, 17 at 80002, at ang subcodes na 2207001, 2207003, 2207008 at 2207032. Ang code 4 na may subcode 2207051 ay hinihinalang spam, kaya agad itong humihinto.
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))Paano tumawag sa API at pangasiwaan ang errors sa Node.js?
Gamit ang parehong helper para sa Node.js 18 o mas bago, na gumagamit ng fetch at walang dependencies. Ang throttled na tawag ay naghihintay ng estimated_time_to_regain_access, ang mga minutong iniuulat ng Meta sa header na X-Business-Use-Case-Usage, o 60 segundo kung wala ito, dahil binibilang ng Meta ang mga tawag na ginawa habang naka-throttle. Minarkahan ng needsNewToken ang mga code na 190 at 102, na hindi kayang ayusin ng anumang retry.
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");
}Paano mag-publish ng larawan at Reel sa Python?
Parehong sumusunod sa container flow. Handa agad ang photo container, kaya diretsong susunod ang media_publish. Muna pinoproseso ang video ng Reel: sinusuri ng function ang status_code kada minuto, hanggang 5 minuto, gaya ng iminumungkahi ng Meta, at nagpa-publish kapag FINISHED, at humihinto kapag ERROR o EXPIRED. Dapat JPEG ang mga image, at nasa public URL ang media.
# 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")Paano mag-publish ng larawan at Reel sa Node.js?
Ang parehong dalawang function, na bawat isa ay nagbabalik ng bagong media ID. Ang container na nasa IN_PROGRESS pa pagkatapos ng limang check ay nananatiling valid hanggang 24 oras pagkatapos itong likhain, kaya sinasabi ng error na suriin ulit ito mamaya, na nakakatipid sa paglikha ng pangalawang container laban sa limitasyong 400 kada araw ng account.
// 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`);
}Paano magbasa ng comments at sumagot sa Python?
Ibinabalik ng GET /<IG_MEDIA_ID>/comments ang mga top-level na comment, pinakabago muna, hanggang 50 kada request, at ang POST /<IG_COMMENT_ID>/replies ay nagpo-post ng pampublikong sagot sa isa rito. Humihingi ang function ng teksto ng bawat sagot sa pamamagitan ng callback na ibibigay ninyo, at nilalaktawan ang mga comment na walang ibinalik na teksto. Hindi maaaring sagutin ang mga nakatagong comment, at ang sagot sa isang reply ay napupunta sa top-level na comment.
# 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)Paano magbasa ng comments at sumagot sa Node.js?
Ang parehong loop sa Node.js. Parehong tawag ang gumagamit ng instagram_business_basic at instagram_business_manage_comments, at kailangan ng username field ang ikalawa. Para sumagot nang pribado, ang POST /<IG_ID>/messages na may recipient.comment_id ay nagpapadala sa nag-comment ng isang DM, sa loob ng 7 araw mula sa comment, at maghihintay ang follow-up hanggang sumagot sila.
// 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));Paano magbasa ng insights sa Python?
Ang account insights ay kumukuha ng period=day na may metric_type=total_value, at bawat metric ay nag-uulat ng total_value.value; ang insights ng post ay nag-uulat ng values[0].value. Ang halimbawa ay humihingi ng reach, views at accounts_engaged para sa account, at reach, views, likes, comments, saved at shares para sa post o Reel, na nakalista sa reference ng Meta para sa pareho. Ang metric na walang data ay iniiwan sa halip na ibalik bilang 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}Paano magbasa ng insights sa Node.js?
Ang parehong dalawang request sa Node.js, na bawat isa ay nagbabalik ng object na may metric name bilang key. Wala sa kanila ang nagpapadala ng breakdown: binabalaan ng Meta na ang paghingi ng breakdown na hindi sinusuportahan ng isang metric ay magpapabagsak sa request na may unknown error, at na ang insights data ay maaaring mahuli ng hanggang 48 oras, kaya basahin ulit ang mga kamakailang post sa bandang huli.
// 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]));
}Paano i-verify ang webhook sa Python?
Sa Flask, gamit ang dalawang route sa iisang path. Sinasagot ng GET ang verification request ng Meta: kapag ang hub.mode ay subscribe at tugma ang hub.verify_token, ibinabalik nito ang hub.challenge bilang plain text, at 403 kung hindi. Kinakalkula ng POST ang sha256= kasama ang HMAC-SHA256 ng raw body gamit ang app secret, inihahambing ito sa X-Hub-Signature-256 sa constant time, at sumasagot ng 200 bago magsimula ang anumang mabagal na gawain.
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 "", 200Paano i-verify ang webhook sa Node.js?
Gamit ang built-in na http module at walang framework. Kinokolekta ang body bilang raw bytes bago ito i-parse, dahil ang na-parse at muling na-serialize na body ay hindi na tugma sa signature na kinalkula ng Meta. Nagre-retry ang Meta ng bigong notification hanggang 36 oras, kaya dapat ding laktawan ng handler ang mga event na naproseso na nito.
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);Anong mga error ng Meta ang dapat i-retry ng code?
Pansamantalang error lamang, dahil ang iba ay magbabalik ng parehong sagot hanggang may magbago: ang file, ang URL, isang permission o ang estado ng account. Ibinibigay ng mga error reference ng Meta ang aksyon para sa bawat code na pinagkakaiba ng mga helper sa itaas:
Paano patakbuhin ang parehong code sa credentials ng easyCoexistence?
Hindi ito maaaring patakbuhin gamit ang token ng easyCoexistence: hindi kailanman ipinamamahagi ang mga token ng Instagram (mga tuntunin ng Meta), kaya ang get_social_credentials at ang GET /api/v1/channels/:id?credentials=1 ng Partner API ay nagbabalik ng ID at API base ng account na walang token. Sa halip, tumatakbo ang parehong gawain bilang MCP tools, sa pamamagitan ng Claude, ChatGPT o ibang MCP client, at gumagana nang walang pagbabago ang mga helper sa itaas sa token mula sa sarili ninyong Meta app.
{
"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. ..."
}Paano gawin ang parehong gawain sa pamamagitan ng MCP connector?
Sa pamamagitan ng pagtatanong sa assistant, o sa pagtawag mismo ng mga tool. Ginagawa at pina-publish ng publish_instagram_post ang container, naghihintay habang pinoproseso ang video, o nag-iiskedyul gamit ang scheduled_at hanggang 90 araw sa hinaharap; sumasagot ang reply_to_comment nang pampubliko, o nang pribado sa pamamagitan ng DM kapag private ay true; ipinapasa ng get_social_insights ang mga pangalan ng metric nang diretso sa Meta; at ipinapasa ng set_social_webhook_destination ang comments, mentions at DMs sa endpoint ninyo, na nilalagdaan ng 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" }
}
]Mga karaniwang pagkakamali
- Pag-hash ng na-parse na JSON. Nilalagdaan ng Meta ang raw bytes, kaya sinisira ng JSON body parser ng framework ang pagsusuri ng X-Hub-Signature-256; panatilihin ang raw body at i-parse ito pagkatapos.
- Pagtawag ulit ng media_publish pagkatapos ng timeout nang hindi muna tumitingin. Kapag ang status_code ng container ay nagbabasa ng PUBLISHED, live na ang post.
- Pagbasa sa code 4 bilang throttling nang walang subcode. Kapag 2207051 ito, ibig sabihin ay pinaghihinalaang spam ng Instagram, at inuulit lamang ng retry ang aksyong kakapigil pa lamang.
- Pagpapadala ng app secret o token mula sa browser o mobile code. Sinasabi ng Meta na ang mga request na may dalang app secret ay dapat nasa server-side code lamang.
US$ 9 hanggang US$ 0.75 kada koneksyon kada buwan, bumababa habang dumarami ang koneksyon, kasama ang unang 3 araw na free trial.
Mga madalas itanong
Kailangan ko ba ng SDK para tumawag sa Instagram API?
Hindi. Ang bawat tawag ay HTTPS request na may access token, kaya sapat na ang requests sa Python o fetch sa Node.js, gaya ng makikita sa mga halimbawa sa pahinang ito.
Bakit nabibigo ang media_publish agad pagkatapos gawin ang Reel container?
Pinoproseso pa ang video: error 9007 na may subcode 2207027. Suriin ang status_code ng container kada minuto at mag-publish kapag nagbasa itong FINISHED.
Anong bersyon ng API ang dapat gamitin ng code?
Ang bersyong sinusuportahan pa ng Meta: v26.0 ang pinakabago, at ang bawat bersyon ay tumatagal ng hindi bababa sa dalawang taon. Ang tawag sa bersyong tinanggal na ay tatakbo sa susunod na pinakalumang bersyong available pa.
Magkano ang gastos ng easyCoexistence para sa API access sa isang Instagram account?
Bawat Instagram account ay isang koneksyon: US$ 9 hanggang US$ 0.75 kada koneksyon kada buwan, bumababa habang dumarami ang koneksyon, kasama ang unang 3 araw na free trial.
Magpatuloy sa pagbabasa
I-connect ang inyong unang channel sa loob ng dalawang minuto.
Walang review ng platform na hihintayin. I-connect ang WhatsApp, Instagram, TikTok o iba pang channel, pagkatapos ay utusan ang inyong AI na mag-post, mag-reply o gumawa ng report, at panoorin itong gumana.
- 3 araw na libre
- Mag-cancel anumang oras
- Official API lang
- Minomonitor 24/7
Na-verify noong