How to Get Instagram User Posts with Python and Paginate the Results
The first Instagram collector most people write assumes a numbered catalog: fetch page 1, then send page=2 or offset=12 and expect the next twelve posts. That request shape does not exist here. user-posts takes a username (or numeric id) and, after the first page, a pagination_token you did not mint. The token is opaque. Treating Instagram like page=2 is the bug — not a missing limit parameter.
This guide is one Python loop that copies the token verbatim, caps how many pages you will buy, stops when the token is missing or repeats, and deduplicates media IDs when windows overlap. Opening the page or copying the snippets does not call anything; a request happens only when you replace the placeholders and run the code.
The Instagram Data API reads publicly visible surfaces over GET. It is not an OAuth Insights product: private-account posts are out of scope, historical completeness is not promised, and like_count / comment_count are collection-time snapshots.
There is no page 2
user-posts has no page, no offset, and no client-chosen page length. Continuation is a sealed cursor. Do not parse it, truncate it, increment it, or paste a token from user-reels (or from hashtag / comments routes that use next_page or end_cursor) into this operation. Adjacent pages can overlap. Page size is whatever items actually contains — a live check once returned 12 rows; treat that as an observation, not a contract.
Copy an authorized key from the dashboard after you sign in. Keep it in OPENDATA_API_KEY on the server. Query URLs include key, so redact them in logs, traces and screenshots; do not embed the value in a frontend bundle. A pasted URL may show YOUR_API_KEY; that string is a dead placeholder, not a live credential.
Every call has two status layers. HTTP 4xx/5xx is transport, auth or quota. HTTP 200 is not success by itself: the gateway envelope still carries code, message and data, and business success is code=200. A handle that does not exist can still return HTTP 200 with exactly {"detail":"Not found"} in data. That is a miss. Record it and move on — do not retry it as if the profile were flaky, and do not insert it as a user.
Username in, token out
Pass username_or_id. The handle instagram and the numeric id 25025320 resolve to the same public account. You can send the handle on every page. Handles change; the numeric id from user-info does not, so a long-running job usually resolves once and stores that id. On a hit, user-info also returns username, follower_count, is_verified and is_private. If is_private is true, skip the feed — profile flags can be visible while posts are not.
First user-posts request: username (or id) only. Omit pagination_token. Posts live in data.items, the author summary in data.user, the continuation on that same data object as pagination_token. Feed each returned token into the next request unchanged until the field is absent.
import os
import time
import requests
BASE = "https://api.opendata-api.com/api/project/instagram"
API_KEY = os.environ["OPENDATA_API_KEY"]
def call(operation, **params):
response = requests.get(
f"{BASE}/{operation}",
params={k: v for k, v in {**params, "key": API_KEY}.items() if v},
timeout=30,
)
if not response.ok:
raise RuntimeError(f"HTTP {response.status_code}")
gateway = response.json()
if gateway.get("code") != 200:
raise RuntimeError(f"Gateway business failure: {gateway.get('message')}")
return gateway.get("data")
def resolve_user(username_or_id):
data = call("user-info", username_or_id=username_or_id)
if not isinstance(data, dict) or data.get("detail"):
return None # business-level miss, e.g. detail Not found
return data
resolve_user("instagram") is optional preflight. The feed loop below accepts either the handle or the stored numeric id.
Budget, repeat tokens, duplicate media IDs
A collector that only stops on “no token” can still run away. Three guards belong in the same loop: a page budget you choose (max_pages), repeated-token protection if the same cursor comes back unchanged, and media-ID deduplication because successive windows overlap. Stamp _collected_at when you observe each item — counts move between runs, so the snapshot time is part of the row.
Keep these fields from each item: id (dedupe and join key), code (shortcode for URLs and later post-detail), taken_at (Unix seconds), caption.text, media_type (1 photo, 2 video, 8 carousel), like_count / comment_count / play_count, plus image_versions2 / video_versions / carousel_media when you need renditions. Those media URLs expire; they are not an archive. data.user confirms ownership before you attribute a mixed pipeline.
def iter_user_posts(username_or_id, max_pages=5):
"""Yield unique posts, following opaque pagination tokens safely."""
token = None
seen_tokens = set()
seen_media = set()
for _ in range(max_pages): # user-configurable page budget
payload = call(
"user-posts",
username_or_id=username_or_id,
pagination_token=token or "",
)
if isinstance(payload, dict) and payload.get("detail"):
break # business-level miss
for item in (payload or {}).get("items") or []:
media_id = item.get("id")
if media_id and media_id not in seen_media:
seen_media.add(media_id)
item["_collected_at"] = int(time.time())
yield item
token = (payload or {}).get("pagination_token")
if not token or token in seen_tokens:
break # no usable continuation, or the token repeated
seen_tokens.add(token)
profile = resolve_user("instagram")
if profile is None or profile.get("is_private"):
posts = []
else:
posts = list(iter_user_posts(str(profile.get("id") or "instagram"), max_pages=3))
print(f"collected {len(posts)} unique posts")
Need Reels only? user-reels takes the same username_or_id and the same opaque-token pattern. Do not reuse a user-posts token there — each operation issues its own cursor. Do not estimate inventory as “page size × pages”; merge by id.
Enrich one shortcode after the loop
user-posts already carries caption, type and engagement snapshots. post-detail is for a single shortcode or URL when you need extra media URLs, a location tag, or Reels clips_metadata. Call it after the loop, on one code you actually need — not once per item inside the budget. The example shortcode DeM-xDCA2W5 is a documented lookup, not a promise that every run still resolves it.
A full instagram.com/p/... (or /reel/, /tv/) URL is valid as code_or_url. Check data.user before trusting attribution. Keep the numeric media id; it joins comments and likes if you add those operations later.
def enrich_shortcode(code_or_url):
data = call("post-detail", code_or_url=code_or_url)
if not isinstance(data, dict) or data.get("detail"):
return None
return data
if posts:
extra = enrich_shortcode(posts[0].get("code") or "DeM-xDCA2W5")
if extra:
print(extra.get("id"), (extra.get("user") or {}).get("username"))
That is the whole job: username in, sealed token around a budgeted loop, one optional shortcode out.
The mistakes that still show up after the script compiles: sending page=2 / offset / a homemade token; decoding or shortening pagination_token; sharing one token across user-posts and user-reels; treating HTTP 200 as a profile when detail is Not found; retrying that miss; enriching every item in the loop; assuming twelve rows per page; storing expired rendition URLs as permanent assets; reading like_count as official Insights; logging request URLs that still contain the key. Stop on those before adding comments, hashtags or location feeds — those routes paginate with their own field names, and mixing them with this token is the same page=2 bug in a different costume.
See user-posts, user-info, post-detail and user-reels. Per-request cost is on pricing.