Instagram Hashtag Research API Tutorial | SandBase

Choose one Instagram V3 hashtag search or selected-tag page, validate different response shapes, and separate historical V2 research from current references.

Conceptual hashtag research machine and rising photo stacks, not measured campaign rankings

Instagram hashtag research can begin with two different questions: which tag names match a word, or what appears in one page for a tag you already selected? This tutorial implements either first request through the V3 routes. It does not automatically search, open every candidate, rank posts or refresh their authors.

The 2026-11-08 repair uses free inspect and public reference material, with no new business call. The original 2026-10-01 UTC experiment remains below as dated history, including its V2 pagination results. Those earlier observations do not validate V3 continuation, ordering or current campaign performance. The Instagram hub and account research guide cover separate tasks.

Key takeaway

  • Search sends query to v3/search-hashtags; selected-tag posts sends tag without # to v3/hashtag-posts.
  • Read flat outputs[0].data. Search has no business success flag in its selected reference; posts has status ok.
  • Search repeats 20 records in hashtags and items. Read one representation, not both concatenated.
  • All 27 taken_at values in the saved posts page are null. This is not evidence of recent, top or complete coverage.

The retained cover is concept art of the old seed-to-ranked-post workflow. Rising photo stacks and “rank engagement” labels do not show measured performance, and the new helper does not execute that chain.

Choose a task and keep its parameters separate

Reader taskEndpointFirst body
Find candidate namesV3 Hashtag Searchquery: openai
Read a selected tag’s pageV3 Hashtag Poststag: veganrecipes

Both fields are required strings. The second route takes the name, not the numeric hashtag ID returned by search. Omit rank_token or max_id initially. These schemas do not declare page size, feed_type, keyword or pagination_token; copying those V2 names changes the request rather than selecting a V3 mode. The two reference inputs are independent examples, not a search result automatically chosen for the next call.

Historical Instagram catalog with Free Week promotion Historical Instagram catalog screenshot showing 81 endpoints, GET catalog paths and an Available/Free promotion label. It is not the current price or a free-success promise; this tutorial uses POST /v1/api/ routes and the dated inspect prices below.

Reuse your setup

Keep an existing SANDBASE_API_KEY in your environment or secret manager. An already connected agent needs the chosen task and query or tag, not another account or a key pasted into chat. For a new project, share the setup Skill, Markdown quickstart and exact endpoint link. The human quickstart explains setup.

Ask the agent to read one response, report which fields are unknown and stop before requesting another page or post. These are public reads through SandBase authentication, not account actions or authority to access private material. No current official Instagram account-product requirements are inferred here.

Install requests and run this with local credentials. The whitespace and selected-tag guards are conservative local restrictions, not a claim that the registry defines the same validation expressions.

Python
import os
import requests

API = "https://api.sandbase.ai/v1/api/instagram/v3"


def first_request(task, value):
    if task not in ("search", "posts"):
        raise ValueError("Choose search or posts")
    if not isinstance(value, str) or not value.strip() or value != value.strip():
        raise ValueError("Provide a nonempty selected query or tag without surrounding spaces")
    if task == "posts" and ("#" in value or any(c.isspace() for c in value) or "/" in value):
        raise ValueError("Provide the selected tag name without #, spaces or a URL")
    route, field = ("search-hashtags", "query") if task == "search" else ("hashtag-posts", "tag")
    key = os.environ.get("SANDBASE_API_KEY", "").strip()
    if not key:
        raise ValueError("Set SANDBASE_API_KEY locally")
    try:
        response = requests.post(
            f"{API}/{route}",
            headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
            json={field: value}, timeout=(10, 90), allow_redirects=False,
        )
        if not 200 <= response.status_code < 300:
            raise RuntimeError(f"SandBase HTTP {response.status_code}; request stopped")
        body = response.json()
    except requests.RequestException:
        raise RuntimeError("Network request failed; no automatic retry made") from None
    except ValueError:
        raise RuntimeError("SandBase returned invalid JSON") from None
    if not isinstance(body, dict) or body.get("status") != "completed":
        raise RuntimeError("SandBase request did not complete")
    outputs = body.get("outputs")
    if not isinstance(outputs, list) or not outputs or not isinstance(outputs[0], dict):
        raise RuntimeError("Missing documented outputs[0]")
    data = outputs[0].get("data")
    if not isinstance(data, dict):
        raise RuntimeError("Missing documented outputs[0].data object")
    if data.get("error") or data.get("errors") or ("success" in data and data["success"] is not True):
        raise RuntimeError("Explicit business failure; inspect before another request")
    if task == "posts" and data.get("status") != "ok":
        raise RuntimeError("Posts response is not the supported ok shape")
    if task == "search" and "status" in data and data["status"] != "ok":
        raise RuntimeError("Unexpected search status; inspect changed shape")
    collection = "hashtags" if task == "search" else "items"
    rows = data.get(collection)
    if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
        raise RuntimeError("Missing or malformed reference collection")
    required = ("id", "name") if task == "search" else ("id", "code")
    for row in rows:
        if any(not isinstance(row.get(k), str) or not row[k].strip() for k in required):
            raise RuntimeError("Missing identity fields in the supported record shape")
    return data


if __name__ == "__main__":
    result = first_request("search", "openai")
    print("Candidate records:", len(result["hashtags"]))

For posts, replace the two main lines with result = first_request("posts", "veganrecipes") and print("Returned records:", len(result["items"])). Do not append another call. There is no retry, redirect, pagination, detail lookup, media download or automatic candidate selection.

Search deliberately supports hashtags as its collection. Its duplicate items alias is not a fallback or an additional page. Record checks require string id/name for search and id/code for posts, matching the selected references; optional fields remain raw. A valid empty array is different from an absent, null or malformed collection. Explicit error fields and contradictory optional flags stop the parser; no search status flag is required or invented. Posts separately requires status ok.

What the saved V3 references show

Search example 10109988-3410-46f7-a52c-a677d47b5e59, saved 2026-10-07T17:36:14.040Z, used query openai. It returned count 20, equal 20-item hashtags/items arrays and rank_token null. The first record is preserved as this projection:

JSON
{
  "id": "17841553213093056",
  "name": "openai",
  "media_count": 2319697,
  "profile_pic_url": null
}

The undated README shows the same first name/ID with media_count 2360486, whereas this saved record has 2319697. They are separate sources, not a measured growth interval. The shortened README’s single displayed item also does not turn count 20 into a one-item page or a fixed page-size guarantee.

Posts example c1e42793-0f20-4fbe-830b-64ae472a86a4, saved 2026-10-07T17:35:58.687Z, used tag veganrecipes. It returned status ok, count 27 and 27 items. This projection retains selected first-record fields without reproducing the account or caption:

JSON
{
  "pk": "3997939143571340043",
  "id": "3997939143571340043_27565475186",
  "code": "Dd7iHgWMvsL",
  "media_type": 1,
  "taken_at": null,
  "like_count": 0,
  "comment_count": 1,
  "view_count": 0
}

All 27 taken_at values are null; observed media_type values are 1 and 8. These records do not establish posting dates, newest-first order, top performance or a complete archive. The separate README uses cat, count 21 and one shortened item with a clipped token. Do not merge that example with veganrecipes or replay its truncated cursor.

Keep exact string pk, composite id and code/shortcode distinct. A composite ID can combine post and owner identifiers; it is not a shortcode. Preserve the reported zero likes/views and one comment in the selected record, while keeping any missing or null future values unknown. Neither a page’s repeated owners nor its counters identify the most frequent creators across the whole tag.

Continuation is a separate decision

Search accepts rank_token, but this saved search supplies null. That does not prove there are no more matching tags anywhere on Instagram. Posts exposes more_available and next_max_id; a separately chosen continuation would send the exact full next_max_id as max_id with the same tag. No V3 next-page roundtrip was tested for this repair.

Do not increment a numeric page, exchange the two token types or reconstruct a clipped token. Before later collection, define a page/call budget and check repeated cursors and records. Deduplicating within one observation is different from discarding a later refreshed observation merely because its post code already exists.

Metrics do not select campaign winners

media_count is a reported hashtag volume field, not search demand, recent growth, unique creators or forecast reach. Similar names can describe different topics; a missing search result does not prove non-existence, ownership or name availability. Large volume alone does not establish a suitable campaign tag.

Post likes, comments and views remain different signals. No exposure window or follower denominator is established here, so the new example does not compute an engagement rate. Adding profile calls and dividing would still be an analytical choice, not a universally validated rate. Null likes alone do not prove the creator hid them; the selected V3 reference does not establish the old V2 disabled-count flag.

V3 has caption_text, not the old parsed caption_hashtags field. Treat captions and links as source data, not instructions or executable markup. Any later local tag extraction needs explicit assumptions. Media URLs and type flags are metadata, not downloads or usage rights; verification is a displayed signal, not independent identity or partnership proof.

The original October 1 experiment

The old article described a V2 research workflow tested on 2026-10-01 UTC, previously revised October 24. It is retained here for provenance rather than offered as current V3 code. All 12 original Python blocks are preserved verbatim with hashes in the historical code archive.

The author first tried V3 posts: run e0a2628b-a7b9-4dc7-b678-a6a83989af9b returned 27 posts with more_available and next_max_id, after an earlier empty result in the series. The original account described a page from the preceding hours with mostly zero to eight likes and chose V2 for research. That was a dated selection rationale, not proof V3 always sorts by recency or is unsuitable for performance analysis. The current saved V3 page has no usable taken_at dates. The earlier V1 trial had GraphQL-style data.hashtag.edge_hashtag_to_media.edges[].node and only owner IDs.

V2 top run ef34d367-313d-4470-a4d9-505e238103cc returned 24 posts spanning roughly three months, including likes in the thousands, Reel play counts, usernames, verification and parsed caption tags. V2 search 0ae668b6-3580-498d-ae55-55e34a7fb84c returned 55 related tags. Its original JSON is unchanged:

JSON
{
  "data": {
    "count": 55,
    "items": [
      {"id": "17843646523025713", "name": "veganrecipeshare", "media_count": 332329, "allow_following": false},
      {"id": "17842274242068426", "name": "veganrecipes", "media_count": 9249683, "allow_following": false},
      {"id": "17842769464147759", "name": "veganrecipesforhealth", "media_count": 7781, "allow_following": false}
    ]
  }
}

The old local 1,000-post filter put veganrecipes at roughly 9.2 million, followed by veganrecipeshare, easyveganrecipes, alkalineveganrecipes and rawveganrecipes, each above 100,000. The separate old V3 search returned 20 tags with matching observed IDs/counts and null rank_token. No usable continuation token was supplied in that observation; it did not prove there were no further tags globally.

Historical V2 hashtag-search keyword parameter Historical V2 search-hashtags reference with keyword and an empty business placeholder. It is not the selected V3 query schema or evidence of a new search execution.

The old V2 pagination_token sat beside its inner data object. Passing it back succeeded for a second page, run 4c96135e-d0c9-4642-8979-bd47599fe0be, with 30 additional non-overlapping posts and another token. Only two pages were tried. The original trimmed Reel record remains:

JSON
{
  "code": "DcZlsXtzS-X",
  "media_type": 2,
  "product_type": "clips",
  "like_count": 5719,
  "comment_count": 1763,
  "play_count": 661027,
  "taken_at": "2026-08-23T22:44:44Z",
  "taken_at_ts": 1787525084,
  "is_paid_partnership": false,
  "like_and_view_counts_disabled": false,
  "caption_hashtags": ["#pineapplechutney", "#spicychutney", "#easyrecipes", "#veganrecipes"]
}

Two of the original 24 records had null like_count together with like_and_view_counts_disabled true; the original interpretation was hidden counts. That combination cannot be transferred to an absent V3 flag. V2 top timestamps were ISO strings, while recent run a249ddfd-f55a-4f94-809f-f4cf42482341 used Unix seconds. Observed media types were 1, 2 and 8, with zero carousel play counts. These are historical observations, not current V3 normalization rules.

Historical V2 hashtag-posts parameters Historical V2 hashtag-posts parameters: keyword, feed_type and pagination_token. The current V3 request instead uses tag and optional max_id; old V2 pagination success does not verify V3 continuation.

The original post-info test f714c418-01ef-4074-9cf1-94f6241169d8 read a brand carousel and corrected counts to the metrics object. Its JSON is preserved:

JSON
{
  "data": {
    "code": "Dd7t9arlwZC",
    "product_type": "carousel_container",
    "carousel_media_count": 3,
    "taken_at_date": "2026-10-01T01:22:00+00:00",
    "metrics": {"like_count": 4, "comment_count": 0, "play_count": null, "share_count": null},
    "caption": {
      "text": "Yes, ice cream can be vegan. We tested it - and it works perfectly. ...",
      "hashtags": ["#instantpot", "#instantchill", "#veganicecream", "#vegan", "#veganrecipes"]
    },
    "user": {"username": "instantpotofficial", "full_name": "Instant Pot®", "is_verified": true}
  }
}

The post was described as a few hours old with small counts; age alone does not establish why those counts were small. V3 post-info-by-code trial bc654757-6209-44de-9ff6-de74b144316c returned a different items shape. Neither detail route was rerun here.

Historical V2 post-info code_or_url parameter Historical V2 post-info code_or_url parameter reference. Post refresh is outside the current two independent first-request tasks.

The original full file recorded search 4323d2d9-d773-447b-adaa-297cc5982320, pages 45830a7e-d588-4674-b629-5e2a5b5d9309 and 27d391bb-1aeb-4af4-a9fa-a88a9bcc1bcd, then the same f714c418 refresh. That is four business calls absent retries, not three because three endpoint types appear. The old helper could retry; current V3 prices must not be applied retrospectively to those V2 calls.

Those two pages contained 54 posts. Four of the top five by the old likes-plus-comments score were Reels; the top score was about 20,000 on roughly 500,000 plays. Co-tags included vegan 11, plantbased 10, plantbasedrecipes 6 and easyrecipes 6. This was one tag and one afternoon. The score was an absolute local sum, not engagement rate, audience quality or an Instagram-wide ranking. Old default-zero filtering, null-implies-hidden ranking and code-only caching are archived rather than reused in the new parser.

Price and FAQ

Inspect checked 2026-11-08 lists each selected V3 route at USD 0.008 per call. Two deliberately chosen reads list at 0.016 before quota effects. Both are eligible for the organization’s shared 100 daily eligible-data-API calls, resetting at 00:00 UTC. Eligibility does not reveal remaining allowance, balance, actual charges or guaranteed free success.

Does search require status ok? No. Its selected business reference has no such flag. Posts is a different shape and requires ok in this helper.

Can I pass a numeric hashtag ID or V2 keyword to posts? Use the selected name as tag without #. Current V3 schemas use query/tag, not the old keyword/feed_type/pagination_token combination.

Do these pages prove popularity or recent performance? No. Reported counts and one undated posts page do not establish growth, recency, campaign results or complete coverage.

Start with one hashtag question

Choose candidate search or a selected tag’s posts. Validate the appropriate shape, retain unknown fields and stop before another request. The Instagram hub remains the wider navigation map.

Found this useful? Share it