Log inStart Free Trial
easyCoexistence Official APIs

Facebook Pages API in Python and Node.js: working examples

Python and Node.js call the Facebook Pages API as plain HTTPS requests to graph.facebook.com/v26.0 with the Page's access token: POST /{page-id}/feed and /{page-id}/photos publish, /{post-id}/comments reads and replies to comments, POST /{page-id}/messages replies in Messenger, GET /{page-id}/insights reads metrics, and an HMAC-SHA256 of the raw body checks X-Hub-Signature-256 on each webhook.

easyCoexistence gives a connected Page these jobs as MCP tools, from publish_facebook_post and reply_to_comment to send_social_dm and get_social_insights, forwards its events signed with X-EC-Signature, and gives your own code the Page ID and API base through get_social_credentials.

caption

The text parameter of a Page photo; Meta's photos reference marks message deprecated there.

X-Business-Use-Case-Usage

Response header whose estimated_time_to_regain_access gives the minutes until throttled calls work again.

RESPONSE

The messaging_type for a reply to a message the Page received, sent inside the 24-hour window.

recipient.comment_id

How a private reply addresses the person who commented, through the same /{page-id}/messages endpoint.

What do the examples need before they run?

A Page ID and that Page's access token, read from /me/accounts with a long-lived user token, plus Python 3 with requests, or Node.js 18 or later, whose built-in fetch needs no package. Each job also needs its permission on the token and its task on the Page, and the examples call Graph API v26.0:

Publish a post or photoPOST /{page-id}/feed and /{page-id}/photos: pages_manage_posts, CREATE_CONTENT
Read and reply to comments/{post-id}/comments and /{comment-id}/comments: pages_manage_engagement, MODERATE
Reply in MessengerPOST /{page-id}/messages: pages_messaging, MESSAGING
Read insightsGET /{page-id}/insights: read_insights, pages_read_engagement, ANALYZE
Check a webhookX-Hub-Signature-256, with the app secret and no token

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

With one helper that the later examples reuse: graph() adds the Page token, sends GET parameters in the query string and POST fields as JSON, as Meta's own examples do, and turns Meta's error object into a GraphError carrying code and error_subcode. It waits and retries only the temporary and rate-limit codes, for as long as X-Business-Use-Case-Usage asks when that header comes back, and raises the rest at once.

Python: graph(), then a post and a photo
import json, os, time
import requests

GRAPH = "https://graph.facebook.com/v26.0"
PAGE_ID = os.environ["PAGE_ID"]
PAGE_TOKEN = os.environ["PAGE_TOKEN"]  # the Page's own token, from /me/accounts
RETRY = {1, 2, 4, 17, 32, 613, 80001}   # temporary or rate limited


class GraphError(Exception):
    def __init__(self, err):
        super().__init__(err.get("message"))
        self.code, self.subcode = err.get("code"), err.get("error_subcode")


def wait_seconds(response, attempt):
    usage = json.loads(response.headers.get("x-business-use-case-usage", "{}"))
    minutes = [u.get("estimated_time_to_regain_access", 0) for v in usage.values() for u in v]
    return max([60 * m for m in minutes] + [30 * 2 ** attempt])


def graph(method, path, retries=3, **fields):
    fields["access_token"] = PAGE_TOKEN
    send = {"params": fields} if method == "GET" else {"json": fields}
    for attempt in range(retries + 1):
        response = requests.request(method, f"{GRAPH}/{path}", timeout=30, **send)
        body = response.json()
        if "error" not in body:
            return body
        err = GraphError(body["error"])
        if err.code not in RETRY or attempt == retries:
            raise err
        time.sleep(wait_seconds(response, attempt))


post = graph("POST", f"{PAGE_ID}/feed", message="Open until 11pm this Friday.")
photo = graph("POST", f"{PAGE_ID}/photos",
              url="https://example.com/menu.jpg", caption="This week's menu")
print(post["id"], photo["post_id"])

How do you publish them in Node.js?

With the same helper in Node.js 18 or later, saved as an .mjs file so that top-level await works, and the built-in fetch in place of a client library. The photo call sends url and caption, the photos edge's text field; Meta answers it with the photo's id and the post_id of the Page post that carries the photo, while the feed call answers with the post's id alone.

Node.js: graph(), then a post and a photo
// Node.js 18 or later, saved as an .mjs file: fetch and top-level await are built in.
const GRAPH = "https://graph.facebook.com/v26.0";
const { PAGE_ID, PAGE_TOKEN } = process.env; // the Page's own token, from /me/accounts
const RETRY = new Set([1, 2, 4, 17, 32, 613, 80001]); // temporary or rate limited

class GraphError extends Error {
  constructor(err) {
    super(err.message);
    this.code = err.code;
    this.subcode = err.error_subcode;
  }
}

function waitMs(response, attempt) {
  const usage = JSON.parse(response.headers.get("x-business-use-case-usage") ?? "{}");
  const minutes = Object.values(usage).flat().map((u) => u.estimated_time_to_regain_access ?? 0);
  return Math.max(30_000 * 2 ** attempt, ...minutes.map((m) => m * 60_000));
}

async function graph(method, path, fields = {}, retries = 3) {
  const url = new URL(`${GRAPH}/${path}`);
  const init = { method };
  const all = { ...fields, access_token: PAGE_TOKEN };
  if (method === "GET") {
    for (const [key, value] of Object.entries(all)) url.searchParams.set(key, String(value));
  } else {
    init.headers = { "Content-Type": "application/json" };
    init.body = JSON.stringify(all);
  }
  for (let attempt = 0; ; attempt++) {
    const response = await fetch(url, init);
    const body = await response.json();
    if (!body.error) return body;
    if (!RETRY.has(body.error.code) || attempt === retries) throw new GraphError(body.error);
    await new Promise((done) => setTimeout(done, waitMs(response, attempt)));
  }
}

const post = await graph("POST", `${PAGE_ID}/feed`, { message: "Open until 11pm this Friday." });
const photo = await graph("POST", `${PAGE_ID}/photos`, {
  url: "https://example.com/menu.jpg",
  caption: "This week's menu",
});
console.log(post.id, photo.post_id);

How do you read and reply to comments in Python?

Read a post's comments with fields, filter=stream for comments at all levels in time order and order=reverse_chronological for the newest first, then reply as the Page by posting a message to the comment's own comments edge. The token must come from someone who can perform MODERATE, or Meta leaves the comment IDs out, and replying needs pages_manage_engagement. paging.next leads further back.

Python: read a post's comments and reply to the questions
# graph() as in the first example
post_id = post["id"]  # {page-id}_{post-id}, as the publish call returned it
page = graph("GET", f"{post_id}/comments", fields="id,message,created_time,can_reply_privately",
             filter="stream", order="reverse_chronological", limit=50)
for comment in page["data"]:
    if "?" in comment.get("message", ""):
        graph("POST", f"{comment['id']}/comments",
              message="Thanks for asking! Our hours are on the Page.")
older = page.get("paging", {}).get("next")  # follow it to read further back

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

The same two calls, with the URL object building the query string: a GET with fields, filter and order, then a POST to /{comment-id}/comments. can_reply_privately, requested in fields, says whether the Page can still send that commenter a private reply, which is worth knowing before the Messenger example below. Keep the IDs of the comments you reply to, so that a rerun does not reply twice.

Node.js: read a post's comments and reply to the questions
// graph() as in the first example
const postId = post.id; // {page-id}_{post-id}, as the publish call returned it
const page = await graph("GET", `${postId}/comments`, {
  fields: "id,message,created_time,can_reply_privately",
  filter: "stream",
  order: "reverse_chronological",
  limit: 50,
});
for (const comment of page.data) {
  if ((comment.message ?? "").includes("?")) {
    await graph("POST", `${comment.id}/comments`, {
      message: "Thanks for asking! Our hours are on the Page.",
    });
  }
}
const older = page.paging?.next; // follow it to read further back

How do you send a Messenger reply in Python?

POST /{page-id}/messages with recipient.id set to the person's Page-scoped ID from the messages webhook, messaging_type RESPONSE and the text. The example catches the two refusals not worth retrying: error 10 with subcode 2534022 or 2018278 when the 24-hour window has closed, and 551 when the person is not available. private_reply() puts recipient.comment_id in place of the ID, for the single message a comment allows within 7 days.

Python: a Messenger reply and a private reply
# graph(), GraphError and PAGE_ID as in the first example
def reply(psid, text):
    """psid: sender.id from the messages webhook, within 24 hours of the person's message."""
    try:
        return graph("POST", f"{PAGE_ID}/messages", recipient={"id": psid},
                     messaging_type="RESPONSE", message={"text": text})
    except GraphError as e:
        if (e.code == 10 and e.subcode in (2534022, 2018278)) or e.code == 551:
            return None  # the window has closed, or the person is unavailable: no retry
        raise


def private_reply(comment_id, text):
    """One Messenger message to the person who commented, within 7 days of the comment."""
    return graph("POST", f"{PAGE_ID}/messages", recipient={"comment_id": comment_id},
                 message={"text": text})

How do you send a Messenger reply in Node.js?

The same request body in JavaScript, with recipient, messaging_type and message sent as JSON by graph(). Meta answers a send it accepts with recipient_id and message_id, worth storing against the conversation. A private reply carries a link back to the comment it replies to, and the conversation goes on in the standard 24-hour window once the person writes back.

Node.js: a Messenger reply and a private reply
// graph(), GraphError and PAGE_ID as in the first example
async function reply(psid, text) {
  // psid: sender.id from the messages webhook, within 24 hours of the person's message
  try {
    return await graph("POST", `${PAGE_ID}/messages`, {
      recipient: { id: psid },
      messaging_type: "RESPONSE",
      message: { text },
    });
  } catch (e) {
    const closed =
      e instanceof GraphError && ((e.code === 10 && [2534022, 2018278].includes(e.subcode)) || e.code === 551);
    if (closed) return null; // the window has closed, or the person is unavailable: no retry
    throw e;
  }
}

function privateReply(commentId, text) {
  // one Messenger message to the person who commented, within 7 days of the comment
  return graph("POST", `${PAGE_ID}/messages`, {
    recipient: { comment_id: commentId },
    message: { text },
  });
}

How do you read Page insights in Python?

GET /{page-id}/insights with a comma-separated metric list, period=day and a since and until window in UNIX seconds; one request covers up to 90 days. Three of these metrics took over from ones Meta retired: page_media_view from page_impressions, page_total_media_view_unique from page_impressions_unique and page_follows from page_fans, while page_post_engagements counts reactions, comments and shares.

Python: four Page metrics for the last 28 days
# graph() and PAGE_ID as in the first example
until = int(time.time())
since = until - 28 * 86400  # one request can cover up to 90 days
metrics = "page_media_view,page_total_media_view_unique,page_post_engagements,page_follows"
data = graph("GET", f"{PAGE_ID}/insights", metric=metrics, period="day", since=since, until=until)
for metric in data["data"]:
    for point in metric["values"]:
        print(metric["name"], point["end_time"][:10], point["value"])

How do you read Page insights in Node.js?

The same call, with since and until computed from Date.now() in seconds. Each metric comes back with its name, its period and a values list of value and end_time pairs, one per day; with since set, the first end_time falls on the day after it, so that day's data is included. The token needs read_insights and pages_read_engagement, from someone with the ANALYZE task.

Node.js: four Page metrics for the last 28 days
// graph() and PAGE_ID as in the first example
const until = Math.floor(Date.now() / 1000);
const since = until - 28 * 86400; // one request can cover up to 90 days
const data = await graph("GET", `${PAGE_ID}/insights`, {
  metric: "page_media_view,page_total_media_view_unique,page_post_engagements,page_follows",
  period: "day",
  since,
  until,
});
for (const metric of data.data) {
  for (const point of metric.values) {
    console.log(metric.name, point.end_time.slice(0, 10), point.value);
  }
}

How do you verify a webhook signature in Python?

Recompute X-Hub-Signature-256 from the raw request body and the app secret, then compare the two in constant time. Meta signs each POST with an HMAC-SHA256 of the payload, keyed with the App Secret from the App Dashboard's basic settings, and writes it after sha256=. Pass the body as bytes, before any JSON parsing: request.body in Django and await request.body() in FastAPI both give the bytes Meta signed.

Python: check X-Hub-Signature-256
import hashlib, hmac, os

APP_SECRET = os.environ["APP_SECRET"].encode()  # App Dashboard, Settings, Basic


def signed_by_meta(raw_body: bytes, header: str) -> bool:
    """raw_body: the request body exactly as received. header: X-Hub-Signature-256."""
    expected = "sha256=" + hmac.new(APP_SECRET, raw_body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected.encode(), (header or "").encode())

# Django:  signed_by_meta(request.body, request.headers.get("X-Hub-Signature-256"))
# FastAPI: signed_by_meta(await request.body(), request.headers.get("X-Hub-Signature-256"))

How do you verify a webhook signature in Node.js?

The same check with node:crypto, which needs the body as a Buffer: in Express, express.raw keeps it unparsed on that route. timingSafeEqual throws on inputs of different lengths, so the length test runs first. Answer 200 quickly and do the work afterwards, since Meta retries failed deliveries and can send an event twice; the verification page covers the hub.challenge handshake that comes before any event.

Node.js: check X-Hub-Signature-256
import crypto from "node:crypto";

const APP_SECRET = process.env.APP_SECRET; // App Dashboard, Settings, Basic

function signedByMeta(rawBody, header = "") {
  // rawBody: a Buffer holding the request body exactly as received. header: X-Hub-Signature-256
  const digest = crypto.createHmac("sha256", APP_SECRET).update(rawBody).digest("hex");
  const expected = Buffer.from(`sha256=${digest}`);
  const given = Buffer.from(header);
  return given.length === expected.length && crypto.timingSafeEqual(given, expected);
}

// Express: app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
//   if (!signedByMeta(req.body, req.get("X-Hub-Signature-256"))) return res.sendStatus(401);
//   res.sendStatus(200); // then work on JSON.parse(req.body) after answering
// });

Which error codes should the code act on?

The ones Meta's error guides tell apart, because each needs a different response: retrying a refused token or a bad parameter only fails again, while a throttled call succeeds after a wait. graph() retries the temporary and rate-limit codes and raises the others for the caller to handle:

190, 102The token was refused, and the subcode says why. A new sign-in is the fix
10, 200 to 299A permission was not granted or was removed. Grant it again
4, 17, 32, 613An app, user or Page rate limit. Stop, wait, then resume gradually
80001Page calls made with a Page token are throttled; the header gives the minutes
368Blocked for policy violations. Wait, and review what was being sent
100An invalid parameter. Fix the request before sending it again
551The person is not available on Messenger. Do not retry
1, 2A temporary issue on Meta's side. Wait and retry

How do you run the same jobs through easyCoexistence?

As MCP tools that Claude, ChatGPT or your own agent calls on a connected Page, with the token held by easyCoexistence. Page tokens are never handed out, so the examples above run on a token from your own Meta app; get_social_credentials returns the Page's ID and the Graph API base. Each job's tool:

Publishpublish_facebook_post with message, link, image_url or video_url, now or at scheduled_at
Commentslist_social_comments, then reply_to_comment; private set to true sends the one Messenger message
Messengersend_social_dm, with recipient_id set to the sender's ID from the forwarded event
Insightsget_social_insights with metrics and a period, or object_id for one post
Eventsset_social_webhook_destination; each forward carries X-EC-Signature, made with the Page's own secret

Common mistakes

  • Calling Page endpoints with a user token. Most of them expect the Page's own token, and calls made with a user or app token count against those rate limits instead of the Page's.
  • Publishing the same text twice in a row. Meta refuses consecutive duplicate posts with error 506, so a job that reruns has to vary the content or skip the post.
  • Adding up daily unique viewers. page_total_media_view_unique counts unique viewers in each period, so daily values do not sum to a month; ask for period days_28 instead.
  • Shipping the Page token to a browser or an app. These calls belong on a server, where the token stays out of reach of anyone who can read the client.
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 Facebook Pages API?

No. The Graph API is HTTPS with JSON, so requests in Python and the fetch built into Node.js 18 or later are enough, as the examples on this page show.

Can the same code post to several Pages?

Yes. /me/accounts returns a separate token for each Page, so keep one per Page and pass the matching PAGE_ID and PAGE_TOKEN; calls made with a Page token count against that Page's own rate limit.

Where does the PSID for a Messenger reply come from?

From the messages webhook: sender.id in each messaging event is the person's Page-scoped ID, unique to that person and Page. User IDs from Facebook Login are app-scoped and do not work with the Messenger Platform.

How much does easyCoexistence cost for a Facebook Page?

Each connected Page counts as one connection, at US$ 9 to US$ 0.75 per connection per month depending on how many you have, and the first 3 days are free; the MCP tools come with it.

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