YouTube Shorts Trend Research API: A Python Workflow

Read one Shorts keyword sample or selected channel page with Python. Preserve missing context, distinguish field shapes, and stop before pagination or enrichment.

Conceptual mechanical research device beneath the YouTube Shorts Trend Research API title

A Shorts result list is a starting sample for research, not a measurement of platform-wide trends. A large view display can describe an older video, a rounded count or a query-dependent result. Before scoring anything, decide whether you want candidates for a keyword or Shorts from one channel you have selected. Those are different requests with different fields and costs.

This 2026-11-08 repair implements one keyword-search page or one independent Channel Shorts request. It checks current free inspect and public references without a new business call. The original 2026-10-25 UTC “AI agents” experiment remains historical evidence, including its token-only HTTP 400 and successful keyword-plus-token continuation. That history does not mean this revision executed another page or retested the old enrichment pipeline.

Key takeaway

  • Search starts with keyword. Channel Shorts starts with one channel_id or channel_url; choose one selector explicitly.
  • Both reference payloads have a shorts array, but search uses url/view_count while Channel Shorts uses video_url/view_count_text.
  • Empty author, channel and publication fields are unavailable information, not permission to invent an identity or freshness score.
  • The helper stops after one response. A token, total_count or has_more flag is not a new continuation or completeness test.

The original cover is conceptual research artwork. Its mechanical device is an illustration, not a working dashboard, a new trend measurement or an automatically executed analysis.

Choose a first task

Your questionCurrent endpointFirst body
Which candidates are returned for this keyword?Shorts Search V2keyword; omit continuation_token and filters for this example
Which Shorts are returned for a selected channel?Channel Shortschannel_id or channel_url, need_format true; omit token

Search is useful when you have a topic. Channel Shorts is useful when you already know whose content you want. A blank channel_id in a search row does not establish the creator; do not infer it from the title or automatically select a similarly named account. For a separate public profile or uploads task, see the channel guide. The YouTube hub is wider navigation, not an instruction to call every endpoint.

Reuse the setup and state the stopping point

If SANDBASE_API_KEY is already configured, reuse it from your environment or secret manager. A connected agent needs the task and keyword or selected channel, not a key pasted into chat. For a new integration, provide the setup Skill, Markdown quickstart, and selected API link. The human quickstart explains the account steps.

A useful agent instruction is: “Read one unfiltered Shorts search page for this keyword, preserve raw values, verify the returned keyword and stop. Do not fetch details, comments, channel data or another page automatically.” Change the task to a selected channel when that is your question. This keeps the research scope visible before another request changes the budget or the sample.

Install requests in your Python environment. The script below uses stricter local selector guards than the registry: it accepts a conventional UC channel ID, or an HTTPS youtube.com/channel/ID URL whose identity can be checked. Other URL forms, handles and names need a separately verified resolution step. This restriction is local to the example, not a claim that the upstream API rejects every other channel URL.

Python
import os
import re
from urllib.parse import urlsplit
import requests

API = "https://api.sandbase.ai/v1/api/youtube/web-v2"
ID_PATTERN = r"UC[A-Za-z0-9_-]{22}"


def first_request(task, *, keyword=None, channel_id=None, channel_url=None):
    expected_id = None
    if task == "search":
        if channel_id is not None or channel_url is not None:
            raise ValueError("Search accepts a keyword, not a channel selector")
        if not isinstance(keyword, str) or not keyword.strip() or len(keyword) > 200:
            raise ValueError("Provide a nonempty keyword of at most 200 characters")
        route, payload = "shorts-search-v2", {"keyword": keyword}
    elif task == "channel":
        if keyword is not None or (channel_id is None) == (channel_url is None):
            raise ValueError("Choose exactly one channel_id or channel_url")
        payload = {"need_format": True}
        if channel_id is not None:
            if not isinstance(channel_id, str) or not re.fullmatch(ID_PATTERN, channel_id):
                raise ValueError("Provide a selected UC channel ID")
            expected_id = channel_id
            payload["channel_id"] = channel_id
        else:
            if not isinstance(channel_url, str) or any(c.isspace() for c in channel_url):
                raise ValueError("Provide a canonical HTTPS channel URL")
            url = urlsplit(channel_url)
            match = re.fullmatch(r"/channel/(" + ID_PATTERN + r")", url.path)
            if (url.scheme != "https" or url.netloc not in ("youtube.com", "www.youtube.com")
                    or url.query or url.fragment or not match):
                raise ValueError("Use https://www.youtube.com/channel/<UC channel ID>")
            expected_id = match.group(1)
            payload["channel_url"] = channel_url
        route = "channel-shorts"
    else:
        raise ValueError("Choose search or channel")
    key = os.environ.get("SANDBASE_API_KEY", "").strip()
    if not key:
        raise ValueError("Set SANDBASE_API_KEY in your environment")
    try:
        response = requests.post(
            f"{API}/{route}",
            headers={"Authorization": f"Bearer {key}", "Content-Type": "application/json"},
            json=payload, 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; inspect locally before another call") 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")
    shorts = data.get("shorts")
    if not isinstance(shorts, list) or any(not isinstance(row, dict) for row in shorts):
        raise RuntimeError("Missing shorts array of objects")
    if task == "search" and data.get("keyword") != keyword:
        raise RuntimeError("Returned keyword does not match the selected query")
    if task == "channel" and data.get("channel_id") != expected_id:
        raise RuntimeError("Returned channel ID does not match the selected channel")
    return data


if __name__ == "__main__":
    result = first_request("search", keyword="OpenAI")
    print("Received fields:", sorted(result))

To choose Channel Shorts by ID, replace the main assignment with result = first_request("channel", channel_id="UCuAXFkgsw1L7xaCfnd5JJOw"). The URL alternative is result = first_request("channel", channel_url="https://www.youtube.com/channel/UCuAXFkgsw1L7xaCfnd5JJOw"). Choose one assignment rather than appending calls. The schema says channel_url is ignored when channel_id is present; this helper rejects that ambiguous combination before network access.

The helper requires completed status and an object at outputs[0].data, then an array of Shorts objects and the expected keyword or channel identity. These checks follow the available reference shapes; they do not promise that upstream data never changes. An empty array is different from a missing payload. HTTP redirects, authorization/budget errors, malformed JSON and incomplete runs stop the request without retrying or echoing the key or upstream error body.

Search: a saved page with missing context

The full public saved Shorts Search example is 13b8ea21-d346-4f60-b74a-4fc193d0b415, created_at 2026-08-20T09:37:20.952Z, with input keyword OpenAI. It contains 25 rows. The following is a projection of its first item, not a new execution and not the README’s separate coding tips example:

JSON
{
  "keyword": "OpenAI",
  "shorts": [
    {
      "video_id": "mtK1nsXUqLs",
      "title": "OpenAI and Anthropic's revenue race: Here's what to know",
      "url": "https://www.youtube.com/shorts/mtK1nsXUqLs",
      "view_count": "2.7K views",
      "author": "",
      "channel_id": "",
      "published_time": ""
    }
  ]
}

The empty author, channel_id and published_time values are meaningful limits on this sample. You cannot calculate age, infer creator identity or produce a channel-relative performance score from those blanks. The URL and video ID identify a candidate for later review; they do not require the agent to fetch more data now.

Search uses url and view_count. Preserve the original display string: a value such as 2.7K views is not a precise integer measurement just because a parser can multiply it. The old parser recognized a few English suffixes and could misread other display formats; the current helper deliberately does no numeric normalization. Missing counts remain unknown rather than zero. Date labels and retrieval timestamps also describe different things.

Twenty-five rows was observed in that saved page. The schema exposes no page-size parameter, and a README that trims a list to one item does not establish a one-item page. The search schema describes keyword as required for the first request, although its unified nullable property is not in a required array. This helper enforces a nonempty first keyword of at most 200 characters and preserves it unchanged.

Evidence card showing the first YouTube Shorts search result Original October 25 search evidence card. Its “AI agents” sample and formatted counts belong to that historical experiment, not the August OpenAI saved page or a new November 8 call.

Channel Shorts: a trimmed reference with a different shape

Channel Shorts has no full saved example in the inspected public model. Its README labels a trimmed response as real, but supplies no execution timestamp or full-page snapshot. It displays one Short, total_count 48, has_more true and a clipped continuation token. The excerpt below retains selected fields from that README and intentionally omits the clipped token and media references:

JSON
{
  "channel_id": "UCuAXFkgsw1L7xaCfnd5JJOw",
  "shorts": [
    {
      "video_id": "TIRgIY2nwOk",
      "video_url": "https://www.youtube.com/shorts/TIRgIY2nwOk",
      "view_count_text": "4.9 thousand views"
    }
  ],
  "total_count": 48,
  "has_more": true
}

This source supports the field paths shown, not a claim that the whole page contained one item or that a new request returned 48 Shorts. Treat total_count as the provider’s reported value in that reference. Do not turn it into a verified channel inventory or a promise of a fixed number of requests to collect everything.

Here the row uses video_url and view_count_text rather than search’s url and view_count. Keep those source fields identifiable if you later design a shared storage format. A direct Short URL, thumbnail or accessibility label is still data; the helper does not download, play or follow it. Display text such as “4.9 thousand views” is rounded and is not safely interpreted by a parser that only knows K/M/B suffixes.

The current Channel Shorts schema has no numeric page size or sort option. Its description of a page is not a verified newest-first or incremental-posts contract. Use one selected channel and inspect what comes back. Empty results and missing optional fields should remain visible rather than being filled by a nearby search sample or a guessed creator.

Continuation is a separate operation

Search and Channel Shorts have separate continuation state. Keep the selected route, keyword or channel, filters and capture context with a response token. Do not copy the clipped README token, manufacture one from a video ID, or reuse a token from a different endpoint. A has_more flag describes the returned observation; it is not evidence that a continuation call was successfully made here.

The current search schema includes sort_by options relevance, upload_date, view_count and rating, plus upload_date filters last_hour, today, this_week, this_month and this_year. This first-request script deliberately sends none of them. A later filtered request is a separate choice that changes the sample. Do not loosen filters automatically after an empty result and then describe the broader page as if it answered the original query.

Channel Shorts documents continuation using its returned token with the same selected channel. Search continuation needs special care because the original experiment below observed a token-only failure. This revision does not claim a fresh resolution of every possible continuation combination. It stops after page one, preserving the information needed to design and test a later request deliberately.

Evidence card showing the successful YouTube Shorts pagination rule Historical October 25 pagination evidence: the original token-only request returned HTTP 400, while keyword plus token succeeded. This is a dated observation, not a new continuation roundtrip.

What the October 25 experiment established

The original article reported live calls with “AI agents” on 2026-10-25 UTC. Its retained evidence cards instead label the date UTC+8; the source does not resolve that timezone discrepancy, so no exact execution timestamp is inferred here. Its unfiltered search returned Shorts, the keyword and a continuation token. The first item had formatted views and empty author/channel fields. A request containing only the continuation token returned HTTP 400; the same token with the original keyword produced another page and a new token. Preserve that distinction when reading the historical evidence rather than teaching token-only pagination as universally successful.

The original combination this_month plus view_count returned an empty shorts array while still returning a token. It did not prove that no related Shorts existed on YouTube. The old video-info-v2 check showed only publish_date, rating, thumbnail_url and video_id; it did not guarantee that every missing creator field could be filled. A separate OpenAI channel-shorts check completed, but did not connect the search candidate to OpenAI.

The original prose described a comments list and a separate comment token, but its comments evidence card shows four comments, top ordering and token absent. That mismatch remains unresolved; it does not confirm a usable historical comment token. This is a different sample, not part of the new first-request implementation. It included no textual run IDs or JSON response fences, so this repair does not fabricate them. The original code blocks, including retries, page loops, display-count parsing and shortlist enrichment, remain verbatim in the historical Python archive. They are archived rather than presented as current runnable defaults.

Historical evidence card showing four top comments and token absent Original comments evidence card, retained as historical context. It shows four top comments and token absent, unlike the old prose description. Comments and sentiment analysis were not re-executed; this sample does not measure all viewers’ demand.

Price and a defensible research record

Free inspect checked on 2026-11-08 lists Channel Shorts at USD 0.001 per call and Shorts Search V2 at USD 0.002. Both are eligible for the organization’s shared 100 daily eligible-data-API calls, resetting at 00:00 UTC. Eligibility is not a remaining-allowance, balance or actual-charge check, and it does not guarantee a free successful request. Independently choosing both is 0.003 before quota effects; this script chooses only one.

Save the selected query or channel, response identity, observed row count and raw values together. If you later compare topics, label each query and collection window rather than mixing pages from different filters. A high view count can motivate closer inspection, but a trend claim needs a defined time basis and a sampling method. One page cannot establish growth, platform-wide popularity or a channel’s typical performance.

FAQ

Can I pass channel_id and channel_url together? The schema says ID takes precedence. This helper requires exactly one selector so you cannot accidentally research a different channel from the URL you intended.

Can search always tell me the creator and publication date? No. They are empty in the saved example. Keep them unknown; another endpoint is a separately selected task, not a guaranteed fix.

Is total_count 48 a complete downloaded channel archive? No. It is a reported value in a trimmed README reference without a full saved page. This revision made no channel business call.

Should I parse every count before using the result? First preserve the raw string. Any later numeric interpretation needs a tested format and must retain approximate or unknown status; the current helper does not score results.

Has pagination been retested? No. The October 25 token-only 400 and keyword-plus-token success are preserved as history. The new example makes one first-page request and stops.

Wrap up

Choose keyword candidates or one channel’s Shorts. Validate the selected reference shape, preserve blanks and display text, and stop before continuation or enrichment. The channel guide and comments guide cover separately scoped next questions.