Log inStart Free Trial
easyCoexistence Official APIs

Instagram API in Python and Node.js: working examples

The Instagram API needs nothing beyond HTTPS, so Python's requests and Node.js's built-in fetch cover it: POST /<IG_ID>/media then media_publish publishes, /<IG_MEDIA_ID>/comments and /<IG_COMMENT_ID>/replies read and reply to comments, /insights returns metrics, and a webhook is checked with an HMAC-SHA256 of the raw body. Each error carries a code and subcode that decide whether a retry can help.

easyCoexistence runs the same jobs as MCP tools for Claude, ChatGPT or your own agent, with the token kept on its side: publish_instagram_post, reply_to_comment, get_social_insights and set_social_webhook_destination, on Meta's official API.

v26.0

The latest Graph API version, introduced on 29 July 2026; v25.0 stays available until 29 July 2028.

Once a minute

How often Meta suggests checking a video container's status_code, for no more than 5 minutes.

50

Most comments one GET /<IG_MEDIA_ID>/comments request returns; replies come back only through field expansion.

2207008

A temporary publishing error, which Meta says to retry 1 to 2 times within 30 seconds to 2 minutes.

sha256=

The prefix in X-Hub-Signature-256, before the HMAC-SHA256 of the payload keyed with the app secret.

What do the examples need?

A runtime, a token and four values. The examples call the Instagram API with Instagram Login on graph.instagram.com; a Unified Login app uses the same paths with the account's ID, on Facebook Login's Graph host with its Business Integration System User token. Python needs the requests package, plus Flask for the webhook, and Node.js needs version 18 or later for its built-in fetch.

  • GRAPH: https://graph.instagram.com/v26.0, the host and the API version.
  • IG_ID: the professional account's ID, the user_id that GET /me returns.
  • TOKEN: a long-lived Instagram User access token, kept on the server.
  • APP_SECRET and VERIFY_TOKEN: for checking webhook requests.

How do you call the API and handle errors in Python?

Through one helper, which the Python examples below share. It sends the token as access_token, raises MetaError with Meta's code, subcode and fbtrace_id, and retries only what Meta calls temporary: codes 1 and 2, the throttling codes 4, 17 and 80002, and the subcodes 2207001, 2207003, 2207008 and 2207032. Code 4 with subcode 2207051 means suspected spam, so it stops at once.

Python: the shared helper (requests)
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))

How do you call the API and handle errors in Node.js?

With the same helper for Node.js 18 or later, using fetch and no dependencies. A throttled call waits for estimated_time_to_regain_access, the minutes Meta reports in the X-Business-Use-Case-Usage header, or 60 seconds without it, since Meta counts calls made while throttled. needsNewToken flags codes 190 and 102, which no retry can fix.

Node.js: the shared helper (fetch, ES module)
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");
}

How do you publish a photo and a Reel in Python?

Both follow the container flow. A photo container is ready at once, so media_publish comes straight after it. A Reel's video is processed first: the function checks status_code once a minute for up to 5 minutes, as Meta suggests, publishes on FINISHED and stops on ERROR or EXPIRED. Images must be JPEG, and the media has to sit at a public URL.

Python: a photo and a Reel
# 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")

How do you publish a photo and a Reel in Node.js?

The same two functions, each returning the new media ID. A container still IN_PROGRESS after five checks stays valid until 24 hours after its creation, so the error says to check it again later, which saves creating a second container against the account's 400 a day.

Node.js: a photo and a Reel
// 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`);
}

How do you read comments and reply in Python?

GET /<IG_MEDIA_ID>/comments returns top-level comments, newest first, up to 50 per request, and POST /<IG_COMMENT_ID>/replies posts a public reply to one. The function asks a callback of yours for each reply's text and skips the comments it returns nothing for. Hidden comments can't be replied to, and a reply to a reply lands on the top-level comment.

Python: read comments and reply
# 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)

How do you read comments and reply in Node.js?

The same loop in Node.js. Both calls use instagram_business_basic and instagram_business_manage_comments, and the username field needs the second. To reply in private instead, POST /<IG_ID>/messages with recipient.comment_id sends the commenter one DM, within 7 days of the comment, and a follow-up waits until they answer.

Node.js: read comments and reply
// 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));

How do you read insights in Python?

Account insights take period=day with metric_type=total_value, and each metric then reports total_value.value; a post's insights report values[0].value. The example asks for reach, views and accounts_engaged on the account, and for reach, views, likes, comments, saved and shares on a post or Reel, which Meta's reference lists for both. A metric without data is left out rather than returned as 0.

Python: account and post insights
# 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}

How do you read insights in Node.js?

The same two requests in Node.js, each returning an object keyed by metric name. Neither sends a breakdown: Meta warns that asking for one that a metric doesn't support fails the request with an unknown error, and that insights data can lag by up to 48 hours, so read recent posts again later.

Node.js: account and post insights
// 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]));
}

How do you verify a webhook in Python?

With Flask, in two routes on one path. The GET answers Meta's verification request: when hub.mode is subscribe and hub.verify_token matches, it returns hub.challenge as plain text, and a 403 otherwise. The POST computes sha256= plus the HMAC-SHA256 of the raw body with the app secret, compares it with X-Hub-Signature-256 in constant time, and answers 200 before any slow work starts.

Python: webhook verification and signature check (Flask)
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 "", 200

How do you verify a webhook in Node.js?

With the built-in http module and no framework. The body is collected as raw bytes before anything parses it, because a parsed and re-serialized body no longer matches the signature Meta computed. Meta retries a failed notification for up to 36 hours, so a handler should also skip events it has already processed.

Node.js: webhook verification and signature check (node:http)
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);

Which Meta errors should the code retry?

Only the temporary ones, since the rest return the same answer until something changes: the file, the URL, a permission or the account's state. Meta's error references give the action for each code the helpers above tell apart:

1, 2Temporary or downtime: wait, then retry
4, 17, 80002Throttling: wait for estimated_time_to_regain_access, then retry
4 with 2207051Suspected spam: stop, since a retry repeats the action
2207001, 2207003, 2207032Server error, download timeout or failed container: try again
2207008Container briefly missing: retry 1 to 2 times within 2 minutes
190, 102Token expired or invalid: refresh it while valid, or sign in again
10, 200 to 299Permission missing or removed: request it at sign-in
25 with 2207050Account restricted: the owner acts in the Instagram app
9 with 2207042Daily publishing limit: try again the next day
9004 with 2207052Media not fetched from the URL: fix the link

How do you run the same code on easyCoexistence's credentials?

You cannot run it on easyCoexistence's token: Instagram tokens are never handed out (Meta's terms), so get_social_credentials and the Partner API's GET /api/v1/channels/:id?credentials=1 return the account's ID and API base with no token. The same jobs run as MCP tools instead, through Claude, ChatGPT or another MCP client, and the helpers above run unchanged on a token from your own Meta app.

What get_social_credentials returns for an Instagram account
{
  "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. ..."
}

How do you do the same jobs through the MCP connector?

By asking the assistant, or by calling the tools yourself. publish_instagram_post creates and publishes the container, waiting while a video processes, or schedules it with scheduled_at up to 90 days ahead; reply_to_comment replies in public, or privately by DM with private set to true; get_social_insights passes metric names straight to Meta; and set_social_webhook_destination forwards comments, mentions and DMs to your endpoint, signed with X-EC-Signature.

MCP tool calls for the same jobs
[
  {
    "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" }
  }
]

Common mistakes

  • Hashing the parsed JSON. Meta signs the raw bytes, so a framework's JSON body parser breaks the X-Hub-Signature-256 check; keep the raw body and parse it afterwards.
  • Calling media_publish again after a timeout without looking. If the container's status_code reads PUBLISHED, the post is already live.
  • Reading code 4 as throttling without the subcode. With 2207051 it means Instagram suspects spam, and a retry repeats the action it just restricted.
  • Sending the app secret or the token from browser or mobile code. Meta says requests carrying the app secret belong in server-side code only.
Doing this with EasyCoexistence

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

Do I need an SDK to call the Instagram API?

No. Each call is an HTTPS request with an access token, so requests in Python or fetch in Node.js covers it, as the examples on this page show.

Why does media_publish fail right after a Reel container is created?

The video is still processing: error 9007 with subcode 2207027. Check the container's status_code once a minute and publish when it reads FINISHED.

Which API version should the code use?

One Meta still serves: v26.0 is the latest, and each version lasts at least two years. A call to a removed version runs on the next oldest version still available.

How much does easyCoexistence cost for API access to an Instagram account?

Each Instagram account is one connection: US$ 9 to US$ 0.75 per connection per month, falling as you add connections, with the first 3 days free.

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