AccediInizia la prova gratuita
easyCoexistence API ufficiali

API Instagram in Python e Node.js: esempi funzionanti

L'API Instagram non richiede nulla oltre HTTPS, quindi requests di Python e il fetch integrato di Node.js bastano: POST /<IG_ID>/media seguito da media_publish pubblica, /<IG_MEDIA_ID>/comments e /<IG_COMMENT_ID>/replies leggono e rispondono ai commenti, /insights restituisce le metriche, e un webhook si verifica con un HMAC-SHA256 del corpo grezzo. Ogni errore riporta un codice e un sottocodice che decidono se un nuovo tentativo può servire.

easyCoexistence esegue le stesse operazioni come strumenti MCP per Claude, ChatGPT o il tuo agente, con il token custodito dal suo lato: publish_instagram_post, reply_to_comment, get_social_insights e set_social_webhook_destination, sull'API ufficiale di Meta.

v26.0

L'ultima versione della Graph API, introdotta il 29 luglio 2026; la v25.0 resta disponibile fino al 29 luglio 2028.

Once a minute

Ogni quanto Meta consiglia di controllare status_code di un container video, per al massimo 5 minuti.

50

Il massimo di commenti restituiti da una singola richiesta GET /<IG_MEDIA_ID>/comments; le risposte arrivano solo tramite field expansion.

2207008

Un errore di pubblicazione temporaneo, per cui Meta consiglia di riprovare da 1 a 2 volte entro da 30 secondi a 2 minuti.

sha256=

Il prefisso in X-Hub-Signature-256, prima dell'HMAC-SHA256 del payload calcolato con l'app secret.

Di cosa hanno bisogno gli esempi?

Un runtime, un token e quattro valori. Gli esempi chiamano l'API Instagram con Instagram Login su graph.instagram.com; un'app con Unified Login usa gli stessi percorsi con l'ID dell'account, sull'host Graph di Facebook Login e con il suo token dell'utente di sistema Business Integration. Python richiede il pacchetto requests, più Flask per il webhook, mentre Node.js richiede la versione 18 o successiva per il fetch integrato.

  • GRAPH: https://graph.instagram.com/v26.0, l'host e la versione dell'API.
  • IG_ID: l'ID dell'account professionale, lo user_id che restituisce GET /me.
  • TOKEN: un token di accesso utente Instagram di lunga durata, conservato sul server.
  • APP_SECRET e VERIFY_TOKEN: per verificare le richieste webhook.

Come si chiama l'API e si gestiscono gli errori in Python?

Tramite una sola funzione di supporto, condivisa dagli esempi Python qui sotto. Invia il token come access_token, genera un MetaError con codice, sottocodice e fbtrace_id di Meta, e riprova solo ciò che Meta definisce temporaneo: i codici 1 e 2, i codici di limitazione 4, 17 e 80002, e i sottocodici 2207001, 2207003, 2207008 e 2207032. Il codice 4 con sottocodice 2207051 indica sospetto spam, quindi si ferma subito.

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))

Come si chiama l'API e si gestiscono gli errori in Node.js?

Con la stessa funzione di supporto per Node.js 18 o successivo, che usa fetch senza dipendenze. Una chiamata limitata attende estimated_time_to_regain_access, i minuti che Meta riporta nell'header X-Business-Use-Case-Usage, oppure 60 secondi se l'header manca, perché Meta conta anche le chiamate fatte durante la limitazione. needsNewToken segnala i codici 190 e 102, che nessun nuovo tentativo può risolvere.

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");
}

Come si pubblicano una foto e un Reel in Python?

Entrambi seguono il flusso a container. Un container di foto è pronto subito, quindi media_publish segue direttamente. Il video di un Reel viene elaborato prima: la funzione controlla status_code una volta al minuto per un massimo di 5 minuti, come consiglia Meta, pubblica con FINISHED e si ferma con ERROR o EXPIRED. Le immagini devono essere JPEG e il media deve trovarsi a un URL pubblico.

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")

Come si pubblicano una foto e un Reel in Node.js?

Le stesse due funzioni, ciascuna delle quali restituisce il nuovo ID del media. Un container ancora IN_PROGRESS dopo cinque controlli resta valido fino a 24 ore dalla sua creazione, quindi l'errore suggerisce di ricontrollarlo più tardi, evitando di crearne un secondo, che peserebbe sul limite di 400 al giorno dell'account.

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`);
}

Come si leggono i commenti e si risponde in Python?

GET /<IG_MEDIA_ID>/comments restituisce i commenti di primo livello, dal più recente, fino a 50 per richiesta, mentre POST /<IG_COMMENT_ID>/replies pubblica una risposta pubblica a uno di essi. La funzione chiede a una tua callback il testo di ogni risposta e salta i commenti per cui non restituisce nulla. I commenti nascosti non possono ricevere risposta, e una risposta a una risposta finisce sul commento di primo livello.

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)

Come si leggono i commenti e si risponde in Node.js?

Lo stesso ciclo in Node.js. Entrambe le chiamate usano instagram_business_basic e instagram_business_manage_comments, e il campo username richiede il secondo. Per rispondere in privato, POST /<IG_ID>/messages con recipient.comment_id invia all'autore del commento un solo DM, entro 7 giorni dal commento, e un eventuale seguito attende la sua risposta.

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));

Come si leggono gli insights in Python?

Gli insights dell'account richiedono period=day con metric_type=total_value, e ogni metrica riporta poi total_value.value; quelli di un post riportano values[0].value. L'esempio chiede reach, views e accounts_engaged sull'account, e reach, views, likes, comments, saved e shares su un post o un Reel, come elenca il riferimento di Meta per entrambi. Una metrica senza dati viene omessa anziché restituita come 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}

Come si leggono gli insights in Node.js?

Le stesse due richieste in Node.js, ciascuna delle quali restituisce un oggetto indicizzato per nome della metrica. Nessuna invia un breakdown: Meta avverte che chiederne uno non supportato da una metrica fa fallire la richiesta con un errore sconosciuto, e che i dati degli insights possono avere un ritardo fino a 48 ore, quindi rileggi i post recenti più tardi.

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]));
}

Come si verifica un webhook in Python?

Con Flask, in due route sullo stesso percorso. La GET risponde alla richiesta di verifica di Meta: quando hub.mode è subscribe e hub.verify_token corrisponde, restituisce hub.challenge come testo semplice, altrimenti un 403. La POST calcola sha256= più l'HMAC-SHA256 del corpo grezzo con l'app secret, lo confronta con X-Hub-Signature-256 in tempo costante e risponde 200 prima che inizi qualsiasi elaborazione lenta.

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

Come si verifica un webhook in Node.js?

Con il modulo http integrato e senza framework. Il corpo viene raccolto come byte grezzi prima di qualsiasi parsing, perché un corpo analizzato e riserializzato non corrisponde più alla firma calcolata da Meta. Meta ritenta una notifica non riuscita per fino a 36 ore, quindi un gestore dovrebbe anche saltare gli eventi già elaborati.

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);

Quali errori di Meta vale la pena ritentare?

Solo quelli temporanei, perché gli altri restituiscono la stessa risposta finché non cambia qualcosa: il file, l'URL, un permesso o lo stato dell'account. I riferimenti errori di Meta indicano l'azione per ciascun codice che le funzioni di supporto sopra distinguono:

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

Come si esegue lo stesso codice con le credenziali di easyCoexistence?

Non si può eseguire con il token di easyCoexistence: i token di Instagram non vengono mai consegnati (termini di Meta), quindi get_social_credentials e GET /api/v1/channels/:id?credentials=1 della Partner API restituiscono l'ID dell'account e la base dell'API senza token. Le stesse operazioni funzionano invece come strumenti MCP, tramite Claude, ChatGPT o un altro client MCP, e le funzioni di supporto sopra funzionano invariate con un token della tua app Meta.

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. ..."
}

Come si fanno gli stessi lavori tramite il connettore MCP?

Chiedendo all'assistente, oppure chiamando tu gli strumenti. publish_instagram_post crea e pubblica il container, attendendo mentre un video viene elaborato, oppure lo programma con scheduled_at fino a 90 giorni in anticipo; reply_to_comment risponde pubblicamente, o in privato via DM con private impostato su true; get_social_insights passa i nomi delle metriche direttamente a Meta; e set_social_webhook_destination inoltra commenti, menzioni e DM al tuo endpoint, firmati con 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" }
  }
]

Errori comuni

  • Calcolare l'HMAC del JSON già analizzato. Meta firma i byte grezzi, quindi il parser JSON di un framework rompe il controllo X-Hub-Signature-256: conserva il corpo grezzo e analizzalo dopo.
  • Richiamare media_publish dopo un timeout senza verificare. Se lo status_code del container risulta PUBLISHED, il post è già online.
  • Leggere il codice 4 come limitazione senza il sottocodice. Con 2207051 significa che Instagram sospetta spam, e un nuovo tentativo ripete l'azione che ha appena limitato.
  • Inviare l'app secret o il token dal codice del browser o dell'app mobile. Meta indica che le richieste con l'app secret devono stare solo nel codice lato server.
Farlo con EasyCoexistence

Da US$ 9 a US$ 0,75 per connessione al mese, con prezzo che scende man mano che aggiungi connessioni, e i primi 3 giorni di prova gratuita.

Domande frequenti

Mi serve un SDK per chiamare l'API Instagram?

No. Ogni chiamata è una richiesta HTTPS con un token di accesso, quindi bastano requests in Python o fetch in Node.js, come mostrano gli esempi di questa pagina.

Perché media_publish fallisce subito dopo la creazione di un container Reel?

Il video è ancora in elaborazione: errore 9007 con sottocodice 2207027. Controlla lo status_code del container una volta al minuto e pubblica quando risulta FINISHED.

Quale versione dell'API dovrebbe usare il codice?

Una versione che Meta continua a servire: la v26.0 è l'ultima, e ogni versione resta attiva per almeno due anni. Una chiamata a una versione rimossa viene eseguita sulla versione precedente ancora disponibile.

Quanto costa easyCoexistence per l'accesso API a un account Instagram?

Ogni account Instagram è una connessione: da US$ 9 a US$ 0,75 per connessione al mese, con prezzo che scende man mano che aggiungi connessioni, e i primi 3 giorni di prova gratuita.

Continua a leggere

Collega il tuo primo canale in due minuti.

Nessuna revisione delle piattaforme da aspettare. Collega WhatsApp, Instagram, TikTok o un altro canale, poi chiedi alla tua AI di pubblicare, rispondere o fare un report, e guardala al lavoro.

  • 3 giorni gratis
  • Disdici quando vuoi
  • Solo API ufficiali
  • Monitorato 24/7

Verificato il