YouTube Comment Analysis API Tutorial | SandBase

Read metadata or one YouTube comment sample with Python. Validate video IDs and response shapes, preserve raw counts, and separate reply tokens and historical tests.

Dark cinematic render of a video player slab branching into comment and reply bubble cards that flow into an agent core

A first comment sample can answer a useful question: what are the returned commenters discussing under this video? It cannot measure what every viewer thinks. Start with a video you have selected, choose a sort, and save one response before deciding whether another page would help. A metadata request is a separate choice when you first need to check the video’s identity or context.

This 2026-11-08 repair provides those two independent first requests. It uses current free inspect and public reference material; no new business request, reply expansion, pagination or sentiment-model call was executed. The original 2026-10-01 UTC observations and JSON remain below as historical evidence, alongside a separately dated October 7 saved reference. The original multi-call Python is archived rather than presented as today’s default workflow.

Key takeaway

  • Choose video metadata or one top-level comments page; the example does not run both.
  • Use an 11-character video_id and the documented outputs[0].data envelope. Missing payload is an error; an empty comments array is a valid shape.
  • Twenty comments was an observed page length, not a page-size contract. Top ranking is not a descending-like sort or a representative viewer survey.
  • Preserve count strings, null values and separate top-level versus reply tokens. This revision tests the parser offline, not continuation in production.

The retained cover is conceptual artwork. Its comment/reply cards and multi-step agent chain are illustrations, not a new measured result or an automatically executed analysis.

Choose the first question

Reader’s questionSelected APIFirst request
Is this the video I intended to research?Video Infovideo_id, language_code en, need_format true
What is visible in one discussion sample?Video Commentssame video_id and formatting, country_code US, sort_by top or newest; omit continuation_token

These routes read public data with a SandBase key. They do not post replies, moderate a channel or grant account-bound access. The YouTube hub distinguishes the wider catalog from these selected reads. The transcript tutorial addresses a different question: what is said in the video, rather than in its comments.

SandBase YouTube API catalog page listing YouTube endpoints with Free (during API Free Week) status Historical YouTube catalog screenshot from the original article. Its API Free Week label, 33-endpoint count and catalog GET paths are not current price or availability evidence. This example uses the vendor-qualified POST Model API routes.

Give your agent a bounded task

Already have a key? Reuse SANDBASE_API_KEY from your environment or secret manager. An already connected agent needs your selected video ID and one task, not another signup or a key pasted into chat. For a new project, give it the setup Skill, Markdown quickstart and the selected API link; the human quickstart explains the account setup.

A useful instruction is: “Read one top-level comments page for this video using top ordering and English/US display preferences. Keep the raw values and stop after the response. Tell me if the request or expected shape fails.” If the question is about metadata, choose info instead. This avoids silently starting a video-to-comments-to-replies-to-LLM pipeline before its scope and cost are understood.

Install requests in your project environment. The following complete script makes one request. Its ID check also restricts characters to the usual ASCII video-ID set; the current schema explicitly specifies an 11-character string. It deliberately accepts an ID rather than attempting to extract one from an arbitrary URL.

Python
import os
import re
import requests

API = "https://api.sandbase.ai/v1/api/youtube/web-v2"


def first_request(task, video_id, sort_by="top"):
    if task not in ("info", "comments"):
        raise ValueError("Choose info or comments")
    if not isinstance(video_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id):
        raise ValueError("Provide one 11-character video ID, not a URL")
    if sort_by not in ("top", "newest"):
        raise ValueError("Choose top or newest")
    payload = {"video_id": video_id, "language_code": "en", "need_format": True}
    route = "video-info"
    if task == "comments":
        route = "video-comments"
        payload.update({"sort_by": sort_by, "country_code": "US"})
    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")
    if task == "info":
        if data.get("video_id") != video_id or not isinstance(data.get("title"), str):
            raise RuntimeError("Video reference shape or selected ID does not match")
    else:
        comments = data.get("comments")
        if not isinstance(comments, list) or any(not isinstance(c, dict) for c in comments):
            raise RuntimeError("Missing comments array of objects")
    return data


if __name__ == "__main__":
    result = first_request("comments", "dQw4w9WgXcQ")
    print("Received fields:", sorted(result))

To select metadata instead, replace the main assignment with result = first_request("info", "dQw4w9WgXcQ"). To select newest comments, use result = first_request("comments", "dQw4w9WgXcQ", "newest"). Replace the assignment rather than appending requests. The script does not retry, follow redirects, paginate or fetch media. It reports a clean error without echoing the key, headers or upstream response body.

The shape checks are conservative checks against the available simplified references. They are not a guarantee that upstream fields never change. A mismatched returned video ID is rejected before attaching metadata to your research record. Comments remain unchanged so optional fields, missing counts and tokens are available for deliberate later handling.

Read the returned evidence carefully

The public saved Video Info example has ID 0db08ecb-a998-4c0c-bdb4-1a0057e0cb39 and created_at 2026-10-07T17:37:11.533Z. The saved Video Comments example is 47d6201e-7702-4398-a94a-4f7b9b722ddf, created_at 2026-10-07T17:37:18.832Z. Both use dQw4w9WgXcQ with the input snapshot containing only video_id. They establish reference shapes, not a new execution with this tutorial’s explicit English settings.

The metadata is a flat object containing video_id and title, with author/channel fields and counts where available. Caption tracks are references, not already downloaded transcript text. Thumbnails, end-screen links and available-country lists are data, not instructions to fetch or play anything. An observed playability_status of OK is not permission to download or republish a video.

The saved comment response contains a comments array and a page-level continuation_token. It contains 20 comments, but the selected schema exposes neither page size nor numeric offset. Do not estimate a complete crawl by dividing a display comment_count by twenty: replies and top-level comments have different scopes, and observed page lengths need not be constant.

Keep plain digit strings, abbreviated strings and unknown values distinct. An empty short_view_count is not zero. A localized date is not an exact timestamp; language_code changes display preferences, not necessarily the language of viewer-written text. The helper chooses English deliberately while the schema defaults language_code to zh-CN. Preserve retrieval time separately if you later store records; do not backfill an exact publication timestamp from “one month ago.”

SandBase API reference for the YouTube web-v2 video-info endpoint Historical Video Info parameter reference: required video_id plus optional language_code and need_format. The older empty example is not a newly retrieved payload; the October 7 saved reference is separately attributed above.

Two token scopes, one stopping point

The response’s top-level continuation_token belongs to the top-level comment list. A comment’s reply_continuation_token belongs to that particular thread and is supplied as continuation_token to the separate Video Comment Replies endpoint. Keep the video ID and parent comment identity with any future continuation state. Tokens are not interchangeable, and a comment ID is not a substitute for a token.

Current reference parameters describe continuation, but no continuation roundtrip was performed for this revision. The new helper omits the token and stops after the first response. If you design pagination later, retain the video, sort and locale, budget it separately and check actual responses. Never reuse a trimmed token from a published sample or infer a full-thread guarantee from one empty token.

Top uses provider ranking. It does not document a strict descending-like order. Newest gives a different sample, not “all comments since last run.” Missing and abbreviated likes prevent exact ranking without additional decisions. A practical research record should name the selected video, sort, locale and number of returned comments; a theme summary should describe that collected sample rather than the entire audience.

SandBase API reference for the YouTube web-v2 video-comments endpoint Historical Video Comments reference with country_code, language_code, need_format, sort_by and continuation_token. It does not declare a configurable page size. No continuation was executed in this repair.

Original October 1 observations, preserved

The following excerpts and run IDs belong to the original 2026-10-01 experiment. Its Pixel video title and figures are retained as recorded, not reverified on November 8. The six-call research pipeline was an old experiment, not the new first-request implementation.

The original public Pixel video was GNuXueQ1BYc. Video Info run 7cdb6ca7-c07e-40c6-bc60-737cfb399591, with repeat a8bbc61e-d8d3-4d45-9167-dbce8db97779, recorded this trimmed payload:

JSON
{
  "title": "Google Pixel 11 Pro | Meet 11",
  "author": "Made by Google",
  "channel_id": "UCIG1k8umaCIIrujZPzZPIMA",
  "channel_handle": "@madebygoogle",
  "publish_date": "2026-08-10T09:18:13-07:00",
  "view_count": "394650",
  "like_count": "7009",
  "comment_count": "600",
  "category": "Science & Technology",
  "is_unlisted": false,
  "playability_status": "OK"
}

On a separate OpenAI livestream, 4659dbe8-0c6e-4cbb-a7af-8c4f44eb42b9 recorded a null comment_count; ca8e3dd0-cbd7-4210-a14a-2805603a3bec recorded an empty comments list and null token. Those observations did not establish whether comments were disabled or upstream returned nothing.

Pixel comments run 6a15e813-0975-424e-a08a-07975dc706d5 returned 20 comments. This original comment excerpt omits the author object:

JSON
{
  "comment_id": "UgyqM6dj...",
  "content": "If only the tensor was half as good as this marketing.",
  "like_count": "157",
  "like_count_a11y": "157 likes",
  "published_time": "1 month ago",
  "reply_count": "2",
  "reply_count_text": "2 replies",
  "reply_continuation_token": "Eg0SC0dOdVh1ZVExQlljGAYy...",
  "reply_level": 0
}

A separate second-page run 21210ef3-0cdd-4ad9-9ad3-9e28a55155d1 recorded 20 comments without ID overlap in that pair of pages; it is not a general duplicate-free guarantee. Run c12ba06d-d2ae-420f-bd99-d72b40069013 observed localized strings such as 32万 (320K) and 1年前 (one year ago). Top-page run 82cafd48-fc3a-480c-ae50-03864d83d026 mixed a recent 17-like comment with older, much larger counts, illustrating why top did not mean descending likes.

The old 36-reply thread test returned eight replies and a null cleaned token (249fe9fe-4f7a-4ef9-b50e-90da4a17ff11), repeated with country US (d965b8af-9927-4708-8f13-4e8632841cb6). Unformatted run f50e9fe6-96bc-42a3-8571-2af0e2c91c4c exposed a token; d1c96510-5c14-41a3-a094-31fc801721b7 recorded another 28 replies. The historical 8+28 total matched that displayed 36; it does not validate a current raw-token parser.

The original end-to-end experiment recorded six calls: info f2fd60da-9f2e-4bd7-a9ec-b3c5e381df31; comment pages 807d5158-e110-47db-b790-8ba9ff74464c and 274438ca-9c43-466d-b44b-d4293d997537; reply samples 1299f8fc-c2a6-4b13-9c93-8d44573909c8, 9b827f63-e3b1-45fc-baf6-2564f12fe5e7 and 3e086713-c5e7-4315-9c1a-ebc059c72cab. It collected 40 top-level comments against a displayed 600, sampled 8/6/4 replies for threads displaying 36/6/4, and found six comments containing a question mark. The original themes—soundtrack praise, Tensor skepticism, battery priorities and upgrade questions—were a reading of that small sample, not a measured audience distribution.

The historical reply experiment is useful evidence of why displayed reply counts and a cleaned null token cannot establish completeness. It is not a maintained recipe for recursively extracting tokens from arbitrary raw payloads. The original code, including retry, count conversion, paging and reply selection, is preserved verbatim in the historical Python archive. It is superseded for current integration; use the bounded helper above.

SandBase API reference for the YouTube web-v2 video-comment-replies endpoint Historical Video Comment Replies parameter reference. Reply expansion and the old raw-token fallback were not revalidated or executed in this revision.

Cost and a useful next decision

Free inspect checked on 2026-11-08 lists each selected endpoint at USD 0.001 per call, eligible for the organization’s shared 100 daily eligible-data-API calls, resetting at 00:00 UTC. Eligibility does not show how much allowance remains or prove a request will be free or successful. One selected request is 0.001 before quota effects; choosing both separately is 0.002. Actual charging must be checked against current pricing and your account.

After one response, decide whether it answers your question. For a launch review, a small labeled sample may reveal questions worth investigating without measuring their prevalence. For support research, inspect the text rather than treating a question mark as proof of a support issue. For sponsorship research, one top-ranked page cannot establish authentic engagement or a creator’s entire audience quality. These are interpretation tasks after the read, not automatic extra API calls.

An empty comments array is worth reporting directly. The October 1 null-count/empty-comments observation did not establish that comments were disabled, deleted or absent across all surfaces. A failed request is also different from a valid empty page. Keep those outcomes separate in your application and ask for another call only when it would resolve a defined uncertainty.

FAQ

Does metadata include a transcript? Caption-track references are not transcript text. Fetching and selecting a track is a separate task with its own endpoint and response checks.

Can I get every comment in one call? No completeness promise follows from the available sample. Twenty comments was observed, not a page-size guarantee; the current example stops after one page.

Does top mean most liked? No strict descending-like sort is documented. Report provider-ranked sampling and keep raw counts rather than replacing unknown values with zero.

Should I retry an HTTP 503 automatically? This example stops. The historical retry succeeded once, but that does not establish a safe or bounded retry policy for current billing and workloads.

Do I need YouTube OAuth? These public read endpoints use your SandBase key. Account-authorized operations are outside this tutorial.

Wrap up

Choose metadata or one comments page for a known video. Validate the documented envelope and the selected reference shape, preserve unknown values, and stop before adding another page or reply thread. Continue from Video Info, Video Comments, or the YouTube API hub when the next question is clear.

For 2026 listed prices on the live SandBase YouTube hub, see Best YouTube API in 2026: Pricing Compared.

Found this useful? Share it