Instagram's official API returns a post's comments only with an access token from the user who created that post, so it can't read a competitor's. ToolzerHub's /v1/instagram/post/comments reads any public post from its shortcode and returns top-level comments. The list is shorter than the count Instagram shows, which includes replies. The script below saves it to CSV; the free Instagram comments export downloads one post's first 25.
What Meta's comments API is for
Meta's comments endpoint lists the comments on posts of accounts you run, or whose owners give your app a token. It returns top-level comments only, 50 per query. Meta counts replies in a post's comments_count, so a list of top-level comments is shorter than the count whenever anyone replied. Business Discovery, Meta's route to other accounts' media, returns counts, not comment text; our post on paging a user's posts covers it. Use Meta's API for your own account: it also writes comments, which ours can't.
Instagram comments with ToolzerHub
We make ToolzerHub. Our Instagram API returns a public post's comments as JSON with one API key and no Meta app. GET /v1/instagram/post/comments takes code (the shortcode after /p/ or /reel/), cursor and count, and costs 1 credit a call. Pass page_info.end_cursor back as cursor until has_next_page is false.
Each comment has pk, text, created_at (Unix seconds), comment_like_count and the author's profile fields. A page holds fewer comments than count asks for: first pages of 10 public posts returned 16 to 24 each, and full exports averaged about 14 per call. Replies are a separate /v3/instagram/post/comments/replies route at 3 credits a call.
Export comments to CSV
Save this as instagram_comments.py. It takes shortcodes or post URLs separated by commas, leaves the author out, and writes a CSV that opens in Excel with emoji intact.
import csv
import os
import re
import sys
import time
from datetime import datetime, timezone
import requests
URL = "https://api.toolzerhub.com/v1/instagram/post/comments"
HEADERS = {"x-api-key": os.environ.get("TOOLZERHUB_API_KEY", "")}
FIELDS = ["post", "comment_id", "created_at", "likes", "text"]
calls = 0
FAILED = object() # marks a post given up on: a 400, a 5xx, or a 503 that outlasted the retries
def cell(value):
# Spreadsheets run text that starts with = + - or @ as a formula; an apostrophe keeps it text.
if isinstance(value, str) and value[:1] in ("=", "+", "-", "@", "\t", "\r"):
return "'" + value
return value
def shortcode(item):
# Accepts a shortcode or a post, reel or tv URL; returns None for anything else.
m = re.search(r"instagram\.com/(?:[^/]+/)?(?:p|reel|reels|tv)/([A-Za-z0-9_-]+)", item)
code = m.group(1) if m else item
return code if re.fullmatch(r"[A-Za-z0-9_-]{5,}", code) else None
def get(params, tries=4):
# 429 and 503 are retryable; the wait comes from the error body or the Retry-After header.
global calls
for attempt in range(tries):
r = requests.get(URL, headers=HEADERS, params=params, timeout=90)
calls += 1
if r.status_code == 400: # malformed request: skip this post, keep the rest of the run
print("bad request:", r.text[:120].replace("\n", " "))
return FAILED
if r.status_code not in (429, 503) or attempt == tries - 1:
if r.status_code >= 500: # any 5xx, or a 503 that outlasted the retries: give up on this post
return FAILED
if r.status_code >= 400: # bad key, no credits or a rate limit that outlasted the retries
sys.exit(f"HTTP {r.status_code}: {r.text[:200]}")
return r.json().get("data") # None when there is nothing to return
try:
wait = r.json()["error"]["details"]["retryAfter"]
except (ValueError, KeyError, TypeError):
wait = None
try:
wait = int(wait or r.headers.get("Retry-After") or 5 * (attempt + 1))
except ValueError:
wait = 5 * (attempt + 1)
time.sleep(min(wait, 60))
def export_post(writer, code, max_pages):
params, seen, pages, more, failed = {"code": code, "count": 50}, set(), 0, False, False
while pages < max_pages:
data = get(params)
if not pages and data is not FAILED and not (data or {}).get("items"):
data = get(params) # re-ask once before calling a post empty
if data is FAILED:
failed = True
break
if not data or not data.get("items"):
break # null data, an unknown code, comments off, none yet, or an empty page
pages += 1
for c in data["items"]:
cid = str(c.get("pk") or c.get("id"))
if cid in seen: # keep one row per comment id
continue
seen.add(cid)
made = datetime.fromtimestamp(c["created_at"], timezone.utc).isoformat(timespec="seconds") if c.get("created_at") else ""
writer.writerow({
"post": code, "comment_id": cid, "created_at": made,
"likes": c.get("comment_like_count") or 0,
"text": cell((c.get("text") or "").replace("\n", " ")),
})
info = data.get("page_info") or {}
more = bool(info.get("has_next_page") and info.get("end_cursor"))
if not more:
break
params["cursor"] = info["end_cursor"]
time.sleep(0.4) # the free plan allows 3 requests a second
if failed:
status = " (gave up on this post: bad request or server error)"
elif not pages:
status = " (nothing returned: unknown code, comments off or none yet)"
elif more and pages < max_pages:
status = " (a page came back empty; more may be available)"
elif more:
status = " (stopped at the page cap, more available)"
else:
status = " (reached the end; top-level comments only, no replies)"
print(f"{code}: {len(seen)} comments, {pages} pages{status}")
return len(seen)
def main(posts, max_pages="50", out="comments.csv"):
total = 0
with open(out, "w", newline="", encoding="utf-8-sig") as f: # the BOM lets Excel read emoji
writer = csv.DictWriter(f, fieldnames=FIELDS)
writer.writeheader()
for item in [p.strip() for p in posts.split(",") if p.strip()]:
code = shortcode(item)
if not code:
print(f"{item}: skipped (not a post shortcode or URL)")
continue
total += export_post(writer, code, int(max_pages))
print(f"wrote {total} comments to {out} in {calls} calls")
if __name__ == "__main__":
if len(sys.argv) < 2:
sys.exit("usage: python instagram_comments.py CODE_OR_URL[,...] [max_pages] [file.csv]")
if not HEADERS["x-api-key"]:
sys.exit("set TOOLZERHUB_API_KEY first")
main(*sys.argv[1:])
python instagram_comments.py DehZj9wggt0,DehUTymF6VL,Dek_RAKjMDJ 50 comments.csv saved 790 comments from three public posts. 43 of the 790 rows have empty text, and they look like GIF comments. created_at runs newest first on every post.
How much of the count you get
The list holds 73% to 86% of Instagram's count on four of five posts we paged to the end, and 38% on the fifth.
| Post | Count Instagram shows | Rows saved |
|---|---|---|
| DehZj9wggt0 | 319 | 274 |
| DehUTymF6VL | 536 | 458 |
| Deb8WwanBzo | 1,626 | 1,188 |
| DeSM5CYPDfd | 939 | 353 |
| DeTUk4sDSp- | 6,845 | 5,269 |
Replies explain most of the gap. /v2/instagram/media/comments returns a reply count per comment, and adding those to its rows brings the first three posts to 95% to 98% of Instagram's count.
What it costs
Each call returns about 14 top-level comments, so 1,000 comments cost about 70 credits. The 6,845-comment post took 384 credits for 5,269 rows. You get 100 free credits a month; $19 buys 10,000 credits that never expire, and plans for higher volume cover more posts. Set your key and run the script on your first post.
See also Instagram's follower list limits and, for another platform, YouTube's comment limits.
We are not affiliated with Instagram.