TikTok Search Insights API: Preserve Query IDs and Audience Context
Make one TikTok Creator Search Insights discovery or detail request, preserve exact query IDs, and interpret sparse demographics without inventing daily volume.
A TikTok search-insight record can contain a precise string ID beside a rounded numeric ID. Choosing the wrong one can send your detail request to the wrong identifier before any editorial analysis begins. This guide starts with that practical boundary: read one discovery page, or inspect one deliberately selected query, preserve the request context and stop. A content-gap label is a provider classification, not a forecast that a new video will perform.
The November 8, 2026 revision checks current public schemas and previously saved captures through offline tests. It makes no new business call. The August discovery sample, October detail sample and original October 25 experiment are separate evidence, even where their fields look compatible. None establishes a newly executed discovery-to-detail workflow.
Key takeaway
- Use the original
query_id_str; never reconstruct it from numericquery_idor a floating-point conversion.- Discovery defaults to limit 20, its schema example is 1, and the saved request used 10. These are different facts.
- Detail explicitly selects
past_30_days; there is no schema default for time_range and the response does not echo the query ID or interval.- Demographic totals differ by dimension. Unknown buckets and missing fields cannot become exact audience percentages or invented zeros.
The retained cover is a conceptual mechanical research device titled TikTok Creator Search Insights API, not a live dashboard, measured content-opportunity ranking or executed agent workflow.
Select a Creator Search Insights request
| Task | Exact API reference | First request |
|---|---|---|
| Inspect one discovery page | Creator Search Insights | all tab, English filter, limit 10, offset 0 |
| Inspect a selected query’s detail | Insight detail | exact query_id_str and deliberately selected past_30_days |
Discovery has no required input. Its schema defaults include tab: all, limit: 20, offset: 0, force_refresh: false, creator_source: general_search, empty category filters and English language filters. The limit example is 1, but that is not a maximum. This tutorial deliberately uses the saved all/en/10/0 selection, without automatically refreshing or requesting a second page.
content_gap, follower_searched, life_style, topics, challenges, sounds and hashtags are other documented tab labels. A separate content_gap choice would change the task; the saved all-tab page was not exclusively gaps. Category and language filters are comma-separated strings rather than arrays. Keep their selected values with the record, and do not assume a language filter proves the language of every returned phrase.
Detail requires only a string query_id_str. Time-range descriptions include past_7_days, past_30_days, past_60_days, past_6_months and custom; none is the schema default. The example chooses past_30_days because that is explicit in the saved input. Optional dimension_list is a comma-separated string of gender,age,country; country maps to returned location, not a required country key. Custom start/end dates use integer seconds, but no custom interval is exercised here.
Connect an agent with a clear stopping point
If a key already exists, reuse local SANDBASE_API_KEY or the project’s secret store; install Python’s requests dependency if needed. An already connected agent needs your chosen discovery settings or exact string ID. It does not need another credential or permission to enrich every row automatically.
For a new project, provide the setup skill and Markdown quickstart. Ask it to implement and test one request first: “Read one all-tab English discovery page at limit 10/offset 0. Keep exact query_id_str and raw unknowns. Do not refresh, continue, call detail/trend/videos, or calculate a publishing score.” If detail is the desired task, select it explicitly with the original string ID and interval. Do not paste the API key into the prompt or log it.
As checked November 8, these two routes list at $0.001 each and are eligible for 100 daily calls shared across eligible organization APIs, resetting at 00:00 UTC. Eligibility is not remaining allowance or guaranteed free success. One selected call lists at $0.001; two intentional calls at $0.002 before quota effects. This inspection does not cover the old trend and related-video routes, and no actual charge was measured.
Python: one request, unchanged payload and request context
Use Model API POST /v1/api/<model>, not catalog GET navigation. This function returns a local object containing the request provenance and the original business payload. The provenance is generated from the request, not claimed as an echoed provider field.
import os
import re
import requests
API = "https://api.sandbase.ai/v1/api/tiktok/app-v3"
def first_request(task, query_id_str=None):
if task == "discovery":
if query_id_str is not None:
raise ValueError("Discovery takes no selected query ID in this example")
route = "creator-search-insights"
params = {"tab": "all", "language_filters": "en", "limit": 10, "offset": 0}
elif task == "detail":
if (not isinstance(query_id_str, str)
or not re.fullmatch(r"[1-9][0-9]*", query_id_str)):
raise ValueError("Provide the original query_id_str, never a numeric conversion")
route = "creator-search-insights-detail"
params = {"query_id_str": query_id_str, "time_range": "past_30_days"}
else:
raise ValueError("Choose discovery or detail")
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=params, 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]")
payload = outputs[0].get("data")
if not isinstance(payload, dict):
raise RuntimeError("Missing documented outputs[0].data object")
if type(payload.get("status_code")) is not int or payload["status_code"] != 0:
raise RuntimeError("TikTok business status is not integer zero")
if task == "discovery":
rows = payload.get("inspiration_list")
if not isinstance(rows, list) or any(not isinstance(row, dict) for row in rows):
raise RuntimeError("Missing or malformed inspiration_list")
for row in rows:
if (not isinstance(row.get("query_id_str"), str)
or not re.fullmatch(r"[1-9][0-9]*", row["query_id_str"])
or not isinstance(row.get("query_text"), str) or not row["query_text"].strip()):
raise RuntimeError("Missing exact query identity or text")
else:
if not any(k in payload for k in ("age", "gender", "location", "demographics")):
raise RuntimeError("No recognized detail fields; inspect changed shape")
for name in ("age", "gender", "location"):
if name in payload:
rows = payload[name]
if (not isinstance(rows, list)
or any(not isinstance(row, dict) for row in rows)):
raise RuntimeError("Malformed present demographic array")
if "demographics" in payload and not isinstance(payload["demographics"], dict):
raise RuntimeError("Malformed demographics summary")
# Keep request provenance separately: detail does not echo ID or time_range.
return {"request": {"model": route, "params": params}, "payload": payload}
if __name__ == "__main__":
result = first_request("discovery")
print("Returned ideas:", len(result["payload"]["inspiration_list"]))For detail, replace the two main lines with result = first_request("detail", "7449584484497752069") and print("Requested query:", result["request"]["params"]["query_id_str"]). Do not append this after discovery unless you deliberately choose both calls. The parser cannot detect a rounded number that someone has already converted back into a plausible string; preserve the original string at acquisition.
The local detail guard accepts sparse or empty present dimension arrays and omitted dimensions, but rejects malformed arrays or a result with no recognized detail fields. It does not invent buckets or require identity echoes that are absent from the reference. Discovery requires a usable exact string ID and query text; optional labels and explanations remain optional. A valid empty list differs from a missing one.
HTTP errors, redirects, malformed JSON, timeouts, non-completed runs and nonzero or invalid business status stop the request. Integer type checking prevents False from passing as zero. Empty status_msg is allowed in the saved successes. There is no automatic retry, and error messages do not expose upstream bodies, signed references or credentials.
The saved discovery page and the precision trap
The saved example 42f36a0a-c7b9-4a27-bd47-5ba6c00c7239, created August 20, 2026 at 07:33:33.045 UTC, used all/en/limit 10 / offset 0. It contains ten records, cursor 10 and has_more true; five records have content-gap labels. The first record is reproduced as an exact trimmed projection:
{
"query_id": 7449584484497752000,
"query_id_str": "7449584484497752069",
"query_text": "new account on tiktok",
"query_labels": [],
"popularity": 87,
"popularity_v2": 4741221,
"video_num": 78782,
"trending_seq": [
45,
70,
74,
78,
85,
85,
87
],
"trending_seq_v2": [
9802,
108332,
295888,
449234,
1106431,
1632089,
4741221
]
}Its numeric ID is 7449584484497752000, while the string is 7449584484497752069. All ten captured numeric IDs differ from their exact strings. This is precision loss in the public capture representation; it does not establish what the upstream originally transmitted. Do not repair the rounded value by guessing its last digits or by converting it to a string.
The first record has no content-gap label and no rec_reason; only four of ten records contain that explanation field. It has textnet categories through layer 4, but those categories do not make every result a verified opportunity. Preserve absent explanations and empty labels. has_follower_searched: false is returned metadata, not proof of a user’s account eligibility or access to private follower data.
Popularity 87, popularity_v2 4741221 and video_num 78782 are provider values/scales. They are not verified searches per month, unique searchers, unmet demand or SEO difficulty. The seven values in each trend array have no established per-point dates or units. Do not rename them seven days, compute daily growth or promote a local arithmetic score to a TikTok metric.
The discovery README is a separate undated empty-request fragment with cursor 20, one displayed record, popularity 71 and popularity_v2 174152. It omits later fields such as query_id_str; the strict helper rejects it as an incomplete discovery record. That rejection does not mean the full API response lacks string IDs. Its cursor is not a universal step, and its cropped record is not the full saved ten-item page.
Detail totals need their own context
The saved detail 95a72578-f6f9-4d74-9db3-342ca63e4d01 was created October 7, 2026 at 17:36:57.101 UTC. It requested the same string ID with explicit past_30_days, but at a different date from discovery. It returns flat age, gender, location and demographics fields, without the selected ID or time-range echo. Preserve request context separately; do not claim a matched returned identity or a time-consistent comparison across those dates.
{
"age": [
{
"category": "total",
"popularity": 433427
},
{
"category": "others",
"popularity": 330399
},
{
"category": "25-34",
"popularity": 49214
},
{
"category": "35+",
"popularity": 36110
},
{
"category": "18-24",
"popularity": 15704
},
{
"category": "16-17",
"popularity": 1400
},
{
"category": "4-15",
"popularity": 600
}
],
"demographics": {
"age": "25-34",
"gender": "unknown",
"location": "United Kingdom"
}
}This exact projection shows the age buckets and provider summary. others: 330399 is larger than 25-34: 49214, so the summary “25-34” is not the largest of every returned category. Gender reports total 493646, unknown 439331, male 29608 and female 24707. Keep unknown as unknown.
Location reports total 401003, with United Kingdom 159147, United States 124437, Brazil 34710, Pakistan 13203 and Nigeria 8802. Those listed countries sum to 340299, not the reported total. Do not invent an “other countries” row from the residual. Age total 433427, gender 493646 and location 401003 also differ; they are reported popularity values, not confirmed person counts with one common denominator. Do not add a total row to its constituent buckets or turn these values into exact population percentages.
The shortened detail README has different totals 355704/398818/324781 and is separate undated reference material. It is not a growth baseline for the complete saved example. The local parser accepts its available shape without upgrading it to a new observation.
Clocks, continuation and internal fields
popularity_updated_at is described in seconds; extra.now, the saved-example timestamp and your own observation time are different clocks. cost_tracker.model_cost, total_cost and extra.latency are internal response fields, not SandBase charges, dollar amounts or independently measured latency benchmarks.
Documented discovery continuation sends the returned cursor as the next offset while retaining tab, category, language and source settings. It does not use continuation_token or blindly add the limit. No continuation roundtrip was executed here. A later paging task needs a call cap plus repeated-cursor and repeated-query checks; has_more alone is not a reason to scan indefinitely.
Banners, recommendations, avatars, favorite/dislike flags and commerce labels remain data. They do not instruct the agent to click, enroll, download or contact anyone. Sparse demographics also do not authorize follow-up trend or video requests. Decide those tasks and budgets separately.
Original October 25 experiment
The original author reported tests of discovery, detail, trend and related videos on October 25, 2026 UTC. The three retained evidence cards instead display UTC+8; that time-zone discrepancy remains unresolved, and this revision does not invent a precise execution instant. There were no textual run UUIDs or JSON blocks in that original article, so none is fabricated for it now.
Its content_gap/Science/en/limit10 first page reported ten ideas, cursor 10 and has_more true. The first idea was mount hood, labelled content_gap, with popularity 70 and video_num 1020. Those observations belong to the older experiment, not the August all-tab sample.
Historical rendered evidence card dated October 25 UTC+8: mount hood, content_gap, popularity 70/video count 1020 and cursor 10. It is not a new browser capture, current ranking or proof of another page being fetched.
The old detail request used past_30_days and age,country, exposing age, location and demographics with sparse dimensions. Its trend endpoint was also reported as tested, but its current contract and results were not revalidated in this repair.
Historical detail card lists past_30_days and age,country, with optional age/location/demographics keys. Its sparse-dimensions note is retained; the display does not establish exact audience shares or an ID echo.
The old related-video call reported ten entries in search_item_list[].aweme_info while aweme_list was empty. The old card shows cursor 10 and has_more 1. These are historical observations of a different endpoint, not a new validation step the current function performs.
Historical related-video card: ten nested posts and cursor/has_more fields. Its local scoring/workflow diagram is archival, not a current recommendation to automatically retrieve media or rank publishing opportunities.
All seven original Python blocks (four English, three Chinese), original setup shell blocks and full articles are in the historical archive and hashes. The old two-page discovery, retry helper and three-call enrichment are no longer active guidance. Its editorial formula replaced missing popularity with zero and supply with one, then inferred momentum from untimed values; that was a local queue aid, not a validated predictor. No new score or universal caching interval is introduced.
FAQ
Does a content-gap label guarantee performance? No. It is a provider label. Preserve its source and evaluate the editorial question separately; popularity alone is not proof of supply shortage.
Is past_30_days the detail default? No schema default is declared. It is the explicit choice used here, retained with the request because the business payload does not echo it.
Should missing demographics trigger another endpoint? No. Sparse dimensions stay sparse. A separate editorial review may be useful, but it requires a separately selected task and budget rather than an automatic enrichment chain.
For account-level research, use the distinct TikTok creator guide; broader capabilities are in the TikTok API hub. First preserve a precise query ID and an honest record of what one response does and does not establish.
For 2026 listed prices on the live SandBase TikTok hub, see Best TikTok API in 2026: Pricing Compared.
Found this useful? Share it