Bilibili Video Comment Analysis API Tutorial | SandBase

Prepare one Bilibili video or comment request from a BV id, validate errors, and interpret dated comment and danmaku evidence without automatic pagination.

Dark cinematic render of a glass video screen streaming bullet-comment light dashes into branching comment bubbles that flow into an agent core

Having a BV id is enough to prepare a first Bilibili request, but it does not tell you whether you need video metadata or a comment sample. Start with that choice. This guide now makes one request through SandBase, checks both the SandBase envelope and the Bilibili result, then stops. The larger comment-and-danmaku experiment from 2026-10-01 remains below as dated evidence, not a newly verified crawler.

Key takeaway

  • Choose web/one-video for a known BV id, or app/video-comments for a first comment page.
  • Comments accept exactly one of bv_id and av_id; mode=3 is hot order and mode=2 is time order.
  • Read the documented outputs[0].data, then check Bilibili’s observed code and data wrapper. Missing fields stay unknown.
  • Both endpoints listed a $0.001 base price and a shared organization quota of 100 eligible calls per UTC day on 2026-11-08. Remaining quota was not checked.

Choose the request before connecting your agent

Starting pointEndpoint and input
A BV id and a question about the video itselfVideo details: required string bv_id
A known video and a question about audience commentsVideo comments: choose bv_id or numeric-string av_id, then select mode

Copy the BV identifier from a public video’s address, such as BV19uhb6mEWd, rather than sending the whole URL as bv_id. You do not need to convert that BV id to an AV id for either of these requests. The comment schema describes the two identifiers as alternatives even though its required array does not enforce the choice; the example validates it locally.

The current comments contract uses integer next_offset, default 1. This example sends that first-page value explicitly. It does not calculate a second cursor, follow reply threads, fetch danmaku or call a model. Hot comments are selected by popularity; they are not a representative survey of everyone who watched the video. Time order changes the sampling order, not that limitation.

  • Key already created: store it locally as SANDBASE_API_KEY or in your secret manager. Do not paste it into agent chat or a committed file.
  • Agent already connected to SandBase: reuse the connection, discover Bilibili and inspect the selected tool’s current schema and pricing.
  • New project: give the coding agent the setup Skill and Markdown Quickstart, plus your BV id and the task you chose. Ask it to prepare one request and explain its cost before execution.

An agent task can be as small as: “Prepare one first-page hot-comment request for BV19uhb6mEWd through SandBase. Reuse my existing connection, inspect the current contract and pricing, and show the request before executing. Do not retry, paginate or call an LLM automatically.”

One request with explicit failure handling

The 2026-11-08 inspection listed base_price: 0.001 for both endpoints and free_quota of 100 per organization, shared across eligible APIs, resetting at 00:00 UTC. This verifies eligibility, not your remaining quota or guaranteed free success. Inspect current pricing and account usage before running; a timeout does not prove that the server never executed the request.

Install requests using python -m pip install requests, configure the key locally and save this as bilibili_first_request.py. Running python bilibili_first_request.py makes one potentially billable request. Select video or comments in the last block; these are alternative runs. The route is the Model API POST /v1/api/bilibili/..., not the historical catalog’s GET /apis/v1/... surface.

Python
import os
import re
import requests


def first_request(task, *, bv_id=None, av_id=None, mode=3):
    if bv_id is not None and (not isinstance(bv_id, str) or
                             not re.fullmatch(r"BV[0-9A-Za-z]{10}", bv_id)):
        raise ValueError("Supply a BV identifier, not a video URL")
    if av_id is not None and (not isinstance(av_id, str) or
                             not re.fullmatch(r"[0-9]+", av_id)):
        raise ValueError("Supply av_id as a numeric string")
    if task == "video":
        if bv_id is None or av_id is not None:
            raise ValueError("Video details require bv_id only")
        path, params = "web/one-video", {"bv_id": bv_id}
    elif task == "comments":
        if (bv_id is None) == (av_id is None):
            raise ValueError("Choose exactly one of bv_id or av_id")
        if type(mode) is not int or mode not in (2, 3):
            raise ValueError("Use mode 3 for hot or 2 for time order")
        params = {"bv_id": bv_id} if bv_id is not None else {"av_id": av_id}
        params.update({"mode": mode, "next_offset": 1})
        path = "app/video-comments"
    else:
        raise ValueError("Choose video or comments")
    key = os.environ.get("SANDBASE_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set SANDBASE_API_KEY locally")
    try:
        response = requests.post(f"https://api.sandbase.ai/v1/api/bilibili/{path}",
            headers={"Authorization": f"Bearer {key}"}, json=params,
            timeout=(10, 90), allow_redirects=False)
        if not 200 <= response.status_code < 300:
            raise RuntimeError(f"SandBase HTTP {response.status_code}; inspect before retrying")
        body = response.json()
    except ValueError:
        raise RuntimeError("SandBase returned invalid JSON") from None
    except requests.RequestException:
        raise RuntimeError("Request failed; check run history before retrying") from None
    if not isinstance(body, dict) or body.get("status") != "completed":
        raise RuntimeError("SandBase run did not complete; inspect status and error")
    outputs = body.get("outputs")
    if not isinstance(outputs, list) or not outputs or not isinstance(outputs[0], dict):
        raise RuntimeError("Missing outputs[0]")
    payload = outputs[0].get("data")
    if not isinstance(payload, dict):
        raise RuntimeError("Missing object at outputs[0].data")
    # The Bilibili wrapper was observed in the dated response below.
    if type(payload.get("code")) is not int or payload["code"] != 0:
        raise RuntimeError("Bilibili failed or omitted its success code")
    data = payload.get("data")
    if not isinstance(data, dict):
        raise RuntimeError("Missing Bilibili data object; do not infer zero activity")
    return data


if __name__ == "__main__":
    # Choose ONE request. Change video to comments for the first hot-comment page.
    data = first_request("video", bv_id="BV19uhb6mEWd")
    print("Data keys:", sorted(data))

A completed SandBase run is not enough: Bilibili can return a provider error inside an HTTP-successful response. The helper requires an integer code=0 and an object at the provider’s data. That wrapper is grounded in the dated sample below, not a guarantee of every business field. It prints keys only; no commenter identities or credentials are printed. An empty object remains empty, and a missing count never becomes zero.

This revision used contract checks and offline tests for the Python example, not a new paid business query. On an error, inspect the run’s status and error before choosing another action. It does not retry a 5xx, a connection failure or an empty result. A real approved response is still needed before you depend on fields such as stat, replies or cursor in your application.

Historical evidence: 2026-10-01

The following screenshots, run IDs and observations belong to the original experiment. Five historical screenshots are retained; their prices, field displays and old navigation are not current quotes. Original multi-call Python blocks are archived in the repository evidence, with their retry and dual-envelope logic marked obsolete. The runnable example above is the current starting point.

SandBase Bilibili API catalog page listing Bilibili endpoints with Free (during API Free Week) status Historical screenshot (2026-10-01): The Bilibili catalog on SandBase: 38 endpoints shown as GET /apis/v1/bilibili/..., with the selected “Get video playurl” endpoint marked Available, Free. This tutorial calls the Model API POST /v1/api/bilibili/... routes instead. The screenshot was captured during API Free Week, when Free was the listed price; that promotion has ended. This screenshot does not establish current eligibility or remaining quota; the two endpoints checked in this revision are described above.

Historical video metadata

The historical test video was a public recap from the tech media channel Kejimeixue, a launch-event recap of the Xiaomi 18 Pro / Pro Max (BV19uhb6mEWd, published 2026-09-23 UTC). Run 11f78f98-533c-463e-8b1f-c8de5c165752 returned this, trimmed from outputs[0].data:

JSON
{
  "code": 0,
  "data": {
    "aid": 117321125400871,
    "bvid": "BV19uhb6mEWd",
    "cid": 42143190519,
    "title": "两分钟发布会 | 小米 18 Pro / Pro Max亮相 小米平板9 小米手环11 小米手表S5 还有咖啡机??",
    "owner": { "name": "科技美学" },
    "pubdate": 1790178608,
    "duration": 710,
    "pages": [{ "cid": 42143190519, "page": 1, "duration": 710 }],
    "stat": {
      "view": 247824, "like": 6310, "coin": 445, "favorite": 741,
      "share": 266, "reply": 2199, "danmaku": 1404
    }
  },
  "message": "OK"
}

The sample reported integer counts; the title said “two minutes,” but duration: 710 means 11 minutes 50 seconds. Use the numeric duration, not the title, for a timeline. stat.reply sizes the comment job and stat.danmaku tells you the count to compare with the historical danmaku sample. The cid is the one id you can’t get from the URL; one-video saves you a call to bilibili/web/video-parts, which returned the same cid for this single-part video (run f3862a4d-034b-451e-b924-c452af230b24). Multi-part collection would require separately verified inputs and a separate request budget.

I didn’t need bilibili/web/bv-to-aid either. The comment endpoints I used accept bv_id directly, and one-video returns the aid anyway. One small note: tname (the category) came back empty on this video.

SandBase API reference for the Bilibili web one-video endpoint Historical screenshot (2026-10-01): The bilibili/web/one-video reference (“Get single video data”): POST /v1/api/bilibili/web/one-video with one required string, bv_id. The documented response example leaves outputs[0].data empty.

Historical comment pagination

I started with bilibili/web/video-comments, which takes bv_id and a page number pn, and switched after it misbehaved. Page 1 (run b1b5caeb-43f0-43de-b4e9-44f20245f03c) returned 20 comments and page.count: 2199. Page 2 (run fa847910-aa82-4166-b3b4-17cf5357f45d) returned zero comments and page.count: 0. A retry of page 2 (6f7e6258-f781-4ffb-b00b-a6b1bc168090) worked, and page 3 (139f2dca-660c-4fa9-9c25-d5caef347687) was empty again. An empty page that looks exactly like “the end” is hard to page against.

The app endpoint was steadier. Its first page (run 98654147-fe5a-4a47-8a2a-b23282e23575) returned 20 comments and a cursor object:

JSON
{
  "all_count": 2199,
  "is_begin": true,
  "is_end": false,
  "mode": 3,
  "name": "热门评论",
  "next": 2,
  "pagination_reply": { "next_offset": "CAEiAggC" },
  "support_mode": [2, 3]
}

There are two candidate cursors here, and only one fits the schema. The reference types next_offset as an integer, and sending the string "CAEiAggC" failed with HTTP 400, expected integer, but got string. Sending cursor.next worked: next_offset: 2 (run 9706405a-a879-4769-a3b5-918945e400b0) returned 20 new comments with no rpid overlap and next: 3, and next_offset: 3 (run af057287-9ad9-44b6-b434-4bb7c0ae93b3) returned another 20 with next: 4. That was a dated pagination experiment, not a revalidated continuation contract; the current example stops after the first page.

Each comment carried rpid, like, rcount, ctime, and content.message, plus a member object with the commenter’s name, avatar, and mid. The historical analysis dropped identity fields. One comment, as kept:

JSON
{ "rpid": "314848758273", "text": "哈哈,我花这钱来买安卓?哈哈哈哈哈", "likes": 92, "replies": 21 }

Use rcount for reply counts, not count. On that comment rcount was 21 and count was 47. The endpoint in the historical thread sample reported 21, matching rcount. I can’t tell from the API what the extra 26 in count represent.

SandBase API reference for the Bilibili app video-comments endpoint Historical screenshot (2026-10-01): The bilibili/app/video-comments reference: optional av_id or bv_id (choose one), mode (3 = hot, 2 = time, default 3), and an integer next_offset described as the pagination cursor, default 1.

Historical thread sample

comment-reply needs the video’s bv_id and the parent comment’s rpid; pn is optional. For the 21-reply thread above, page 1 (run b3d5734d-0e61-4890-9cab-ab4e37b4800b) returned 20 replies with page: {count: 21, num: 1, size: 20} and a root object holding the parent comment. Page 2 (run 54035a3e-044e-4bfa-8247-48a10125db05) came back empty with count: 0, the same failure as the web comments endpoint. The retry (1d3c6dc2-a2ba-4fd3-b883-bbd68c9b0c72) returned page.num: 2 and count: 21. The archived code retried that case. The current helper does not retry: missing or empty data needs inspection before another request.

Replies are where clean_text matters. On that page, 15 of 20 began with 回复 @<name> : (“Reply @:”), which puts another user’s handle into your data. Stripping that prefix keeps the reply readable (in one case, a short note on the typical price of a mainland-China iPhone Air 12GB+256GB) without the handle.

SandBase API reference for the Bilibili web comment-reply endpoint Historical screenshot (2026-10-01): The bilibili/web/comment-reply reference (“Get reply to the specified comment”): required bv_id and rpid strings, plus an optional integer pn for the page number.

Historical danmaku sample

This is the step that surprised me most. The reference types outputs[0].data as “object | array”. For danmaku (run 3a0efcf1-8b87-43bd-a60f-b3393d4f8ce2) it was a 123,221-character XML string. Trimmed:

XML
<i>
  <chatid>42143190519</chatid>
  <maxlimit>1500</maxlimit>
  <d p="99.22400,1,25,16777215,…">懂了:pro性能不足 max烫手</d>
  <d p="390.45500,5,25,16765698,…">我为什么要在手机背屏上弹吉他?</d>
</i>

Each <d> element is one danmaku. Its p attribute is a comma-separated list. On this video the first field always fell between 0.7 and 707.9, inside the 710-second duration, so I read it as the playback offset in seconds. Later fields include what looks like a per-sender hash. The historical analysis kept only the offset and text.

Count what you get. Here the XML held 1,404 <d> elements, exactly stat.danmaku. On a second, older video (BV1M1421t7hT, stat.danmaku 3,281), the same endpoint returned 1,200 elements with maxlimit 1,000 (run 196f4179-b89e-457b-ae43-88828b7bef66). So for busy videos, treat danmaku as a sample, and don’t report its totals as the video’s totals.

SandBase API reference for the Bilibili web video-danmaku endpoint Historical screenshot (2026-10-01): The bilibili/web/video-danmaku reference (“Get Video Danmaku”): one required string, cid. The example response shows outputs[0].data as an empty object, while my live call returned an XML string.

Historical aggregate result

On 2026-10-01, I ran the archived workflow end to end. It made 11 calls: one-video (a8abc9c6-d802-410a-8e47-01192919cc77), three comment pages (ca89f260-162e-429b-a9c4-2bb79ea01195, 7bcadf99-7938-47d5-80fd-2a7505e0b9ca, 647f6ca4-0535-46f2-a59b-ae913ef4373e), six reply pages across three threads (first d8fe09de-1123-4096-a067-33bab9194d8f), and one danmaku call (e3c4c8af-d0b7-44ba-84b4-1c630fc8fc72). It collected 60 hot comments out of 2,199, sampled 40, 27, and 30 replies from threads of 54, 27, and 30, found 9 comments with a question mark, and read all 1,404 danmaku.

The danmaku timeline was front-loaded: 210 in the first minute, 184 in the second, a low of 55 in the tenth minute, and a bump to 163 in the eighth. The most repeated danmaku were digits (“0” 99 times, “2” 33 times, “1” 30 times). The API can’t tell me what viewers were answering, but the “0”s clustered around 40 and 460 seconds, so that’s where I’d look in the video.

My reading of the 60 comments, not a measured distribution: the price dominated. The most-liked comment (368 likes) argued that brands now build the national subsidy into launch pricing, others compared the price with iPhones, and a few questioned the rear screen and privacy display. This was an editorial reading of a sample, not a measured sentiment distribution. A future model summary would be a separate, approved workflow.

Original evidence scope (2026-10-01)

ItemStatus
POST /v1/api/bilibili/web/one-video with bv_idDocumented in the reference
POST /v1/api/bilibili/app/video-comments with bv_id/av_id, mode, integer next_offsetDocumented in the reference
POST /v1/api/bilibili/web/comment-reply with bv_id, rpid, pnDocumented in the reference
POST /v1/api/bilibili/web/video-danmaku with cidDocumented in the reference
Envelope id / status / model / outputs[0].dataDocumented in the reference
Upstream wrapper {code, data, message} with stat, aid, cid, owner, pagesObserved only
Comment rpid, like, rcount, content.message, and cursor.next / is_endObserved only
Reply page.count / num / size and rootObserved only
Danmaku as an XML string, first p field as playback secondsObserved only
Danmaku capped below stat.danmaku on a busier videoObserved only
Empty pages with count: 0 on web comment and reply endpointsObserved only

Applying the evidence to a new video

For a launch review, inspect one sample before deciding whether another page would answer a specific question. Preserve the BV id, retrieval date, sorting mode and request parameters with your notes. A top-comment sample can identify questions to investigate; it cannot measure sentiment among all viewers or prove why a video performed well. Playback-aligned danmaku analysis needs a separate, verified collection step and actual numeric duration.

Strip commenter identities before sharing a research summary: avoid copying member, mid, avatars or reply prefixes such as 回复 @name : when they are unnecessary to the question. Keep missing likes, reply counts and unavailable pages distinct from real zeros. Do not turn an error into an empty dataset and then report that nobody commented.

FAQ

Do I need a Bilibili cookie? The two selected SandBase schemas take video identifiers and comment options, not Bilibili credentials. Authenticate with your SandBase key; this guide does not access private or account-bound content.

Is the first request free? Both inspected endpoints are eligible for the shared 100-call daily organization quota. Remaining quota was not checked; current base price is $0.001 each. Recheck usage and pricing before execution.

Can I get the newest comments? Use integer mode=2 for time order; mode=3 is the default hot order. The first-page sample uses integer next_offset=1.

Does an empty response prove there are no comments? No. Check both execution and provider status. Missing data stays unknown; even successful hot-comment sampling does not establish complete coverage.

Should I copy the historical cursor string? No. The selected input is an integer. The 2026-10-01 experiment found that a string cursor failed while cursor.next worked, but this revision did not retest continuation. Verify a real response before implementing pagination.

For the wider endpoint map, read the Bilibili API hub, or the separate creator research guide. Keep your first task to one video and one explicit request.

For a 2026 pricing comparison of the live SandBase Bilibili hub, see Best Bilibili API in 2026: Pricing Compared.

Found this useful? Share it