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 で検証します。各エラーにはコードとサブコードがあり、それによって再試行が有効かどうかを判断できます。
easyCoexistence は、Claude、ChatGPT、またはご自身のエージェント向けに、同じ処理を MCP ツールとして実行します。
2026 年 7 月 29 日に導入された最新の Graph API バージョンです。v25.0 は 2028 年 7 月 29 日まで利用できます。
動画コンテナの status_code を確認する間隔として、Meta が推奨するものです。確認は最長 5 分間続けます。
1 回の GET /<IG_MEDIA_ID>/comments リクエストで返されるコメントの上限数です。返信はフィールド展開でのみ返されます。
一時的な公開エラーです。Meta は 30 秒から 2 分以内に 1 回から 2 回の再試行を勧めています。
X-Hub-Signature-256 の接頭辞です。その後に、アプリシークレットを鍵としたペイロードの HMAC-SHA256 が続きます。
サンプルには何が必要ですか?
実行環境、トークン、4 つの値です。サンプルは graph.instagram.com 上の Instagram Login を使って Instagram API を呼び出します。Unified Login アプリは、同じパスを、アカウントの ID を使い、Facebook Login の Graph ホストで、その Business Integration System User トークンとともに利用します。Python には requests パッケージと、Webhook 用の Flask が必要です。Node.js では組み込みの fetch を使うため、バージョン 18 以降が必要です。
- GRAPH: https://graph.instagram.com/v26.0。ホストと API バージョンです。
IG_ID: プロフェッショナルアカウントの ID です。GET /me が返すuser_idです。- TOKEN: 長期間有効な Instagram User アクセストークンです。サーバー側に保管します。
APP_SECRETとVERIFY_TOKEN: Webhook リクエストの検証に使います。
Python で API を呼び出し、エラーを処理するには?
以下の Python サンプルが共有する 1 つのヘルパーを通じて行います。トークンを 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 を使う同じヘルパーを通じて行います。スロットリングされた呼び出しは、X-Business-Use-Case-Usage ヘッダーで Meta が報告する分数である estimated_time_to_regain_access を待ちます。ヘッダーがない場合は 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 で写真とリールを投稿するには?
どちらもコンテナのフローに従います。写真のコンテナはすぐに準備できるため、その直後に media_publish を呼び出します。リールの動画は先に処理されます。関数は Meta の推奨どおり、最大 5 分間、1 分ごとに status_code を確認します。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 で写真とリールを投稿するには?
同じ 2 つの関数で、それぞれ新しいメディア ID を返します。5 回の確認後もまだ IN_PROGRESS のコンテナは、作成から 24 時間まで有効です。そのためエラーは、後でもう一度確認するよう案内します。これにより、アカウントの 1 日 400 件の上限を、2 つ目のコンテナ作成で消費せずに済みます。
// 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 は、トップレベルのコメントを新しい順に、1 リクエストあたり最大 50 件返します。POST /<IG_COMMENT_ID>/replies は、1 件のコメントに公開返信を投稿します。関数は、ご自身が用意したコールバックに各返信のテキストを問い合わせ、テキストが返されなかったコメントはスキップします。非表示のコメントには返信できません。返信への返信は、トップレベルのコメントに投稿されます。
# 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 日以内であれば、コメント投稿者に DM を 1 件送れます。フォローアップは、相手が返信するまで待ちます。
// 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 を、投稿またはリールについて 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 で同じ 2 つのリクエストを行い、それぞれメトリクス名をキーとするオブジェクトを返します。どちらも 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 を使い、同じパス上の 2 つのルートで行います。GET は Meta の検証リクエストに応答します。hub.mode が subscribe で、hub.verify_token が一致する場合は、hub.challenge をプレーンテキストで返します。そうでない場合は 403 を返します。POST は、生のボディとアプリシークレットから sha256= 付きの HMAC-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 のトークンは決して渡されないため、get_social_credentials と Partner API の GET /api/v1/channels/:id?credentials=1 は、トークンなしでアカウントの ID と API のベースを返します。これは Meta の規約によるものです。代わりに、同じ処理を 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 に設定して DM で非公開に返信します。get_social_insights はメトリクス名をそのまま Meta に渡します。set_social_webhook_destination は、コメント、メンション、DM をご自身のエンドポイントに転送し、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 は、アプリシークレットを含むリクエストはサーバー側のコードにのみ置くべきだとしています。
トークンは easyCoexistence 側で保持されます。publish_instagram_post、reply_to_comment、get_social_insights、set_social_webhook_destination を、Meta の公式 API 上で動作させます。料金は接続 1 件あたり月額 US$ 9 から、接続を増やすほど下がり US$ 0.75 まで。最初の 3 日間は無料です。
よくある質問
Instagram API を呼び出すには SDK が必要ですか?
いいえ。各呼び出しはアクセストークン付きの HTTPS リクエストなので、このページのサンプルが示すとおり、Python の requests や Node.js の fetch で十分です。
リールのコンテナを作成した直後に media_publish が失敗するのはなぜですか?
動画がまだ処理中だからです。エラー 9007、サブコード 2207027 が返ります。コンテナの status_code を 1 分ごとに確認し、FINISHED と表示されたら公開してください。
コードでは、どの API バージョンを使うべきですか?
Meta が現在提供しているバージョンのいずれかです。v26.0 が最新で、各バージョンは少なくとも 2 年間利用できます。削除されたバージョンへの呼び出しは、利用可能な次に古いバージョンで実行されます。
easyCoexistence は、Instagram アカウントの API アクセスにいくらかかりますか?
Instagram アカウントは 1 つの接続として数えられます。料金は接続 1 件あたり月額 US$ 9 から、接続を増やすほど下がり US$ 0.75 まで。最初の 3 日間は無料です。
続きを読む
最初のチャンネルを 2 分で接続しましょう。
プラットフォームの審査を待つ必要はありません。WhatsApp、Instagram、TikTok などのチャンネルを接続して、AI に投稿、返信、レポートを任せてみてください。
- 3 日間無料
- いつでも解約可能
- 公式 API のみ使用
- 24/7 監視
確認日