Xigua Video Research API Tutorial

Check one Xigua search page or a known video record, distinguish empty cards from video IDs, and validate each response without automatic follow-up calls.

Dark cinematic render of a Xigua search resolving into a video and a comment thread feeding an agent core

A successful Xigua search is not necessarily a list of videos. The saved public example examined for this repair says count: 10 and has_more: true, yet its results contains an empty-content card with no usable video ID. If an agent treats that card’s wrapper ID as an item_id, the next request starts from the wrong input.

This 2026-11-08 repair uses free inspect and public references, with no new business request. It replaces the old automatic search → detail → comments flow with two independent first requests. The original 2026-09-27 UTC experiment and 2026-10-01 endpoint-change note remain dated history. The Xigua API hub covers the broader catalog.

Key takeaway

  • Search one page with keyword and explicit integer offset: 0; inspect nested cards before deciding whether any usable candidate exists.
  • For a known numeric video ID, call one-video directly with string item_id. A search-card wrapper ID is not that video ID.
  • Read completed outputs[0].data. Search checks integer err_code: 0; single-video checks message: "success" and an inner data object.
  • Neither a successful search nor the selected metadata route guarantees a title, transcript, downloadable video or a complete research report.

The retained cover is conceptual artwork. Its fictional names, 1,250,000 search results, 623K views, 1,243 comments and analysis labels are not API measurements. The pictured search-to-comments chain is historical concept art, not the current one-request procedure.

Choose one task before connecting

Your starting pointSelected endpointRequest in this guide
A topic to investigateSearch videokeyword, integer offset: 0
An already known numeric video IDSingle video informationstring item_id

The search schema also exposes integer min_duration and max_duration in seconds, plus string order_type. This first request omits those filters. It does not invent sort values or claim to validate every filter combination. The current schema gives offset a default of zero; the example sends it explicitly so the first-page intent is visible.

The selected single-video route is a lighter metadata route with related-video information described by the reference. Do not silently replace it with one-video-v2, a playback-URL route or a comments endpoint. Those are distinct capabilities, inputs and budgets. Public, read-only access through SandBase still requires a SandBase key; it is not account authorization to post or read private content.

Historical Xigua catalog and endpoint navigation Historical endpoint screenshot retained from the original tutorial. It is navigation evidence, not a fresh availability, price or execution check; the seven entries and one-video-v2 listing are historical.

Set up from where you are now

Already have a key? Configure SANDBASE_API_KEY in the runtime or secret manager used by this project. Do not paste it into a prompt, article, screenshot or commit. Check the actual runtime configuration when authentication fails rather than having an agent create another account automatically.

Already connected an agent? Give it the exact route and one task. Ask it to reuse its configured credentials, make one request, validate the layers and identify missing fields. A broad instruction such as “research this topic” can otherwise turn an empty or ambiguous first result into repeated requests.

For a new project, supply SKILL.md and quickstart.md, then say: “Search one page for this keyword; do not fetch candidate details, paginate or read comments.” If you already know the ID, choose one metadata lookup instead. The human quickstart explains setup. Install requests in the Python environment that will run the script.

One request with endpoint-specific checks

Python
import os
import re
import requests


def first_request(task, value):
    if task not in ("search", "video"):
        raise ValueError("Choose search or video")
    if not isinstance(value, str) or not value.strip():
        raise ValueError("Supply a nonempty string")
    if task == "video" and not re.fullmatch(r"[0-9]+", value):
        raise ValueError("item_id must be a numeric string, not a card ID or URL")
    key = os.environ.get("SANDBASE_API_KEY", "").strip()
    if not key:
        raise RuntimeError("Set SANDBASE_API_KEY locally")
    path = "search-video" if task == "search" else "one-video"
    params = {"keyword": value, "offset": 0} if task == "search" else {"item_id": value}
    try:
        response = requests.post(
            f"https://api.sandbase.ai/v1/api/xigua/app-v2/{path}",
            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"HTTP {response.status_code}; inspect access and budget before retrying")
        body = response.json()
    except ValueError:
        raise RuntimeError("Response was not valid JSON") from None
    except requests.RequestException:
        raise RuntimeError("Network request failed; no automatic retry") 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 outputs[0]")
    payload = outputs[0].get("data")
    if not isinstance(payload, dict):
        raise RuntimeError("Missing business object at outputs[0].data")
    if task == "search":
        if type(payload.get("err_code")) is not int or payload["err_code"] != 0:
            raise RuntimeError("Search business status was not err_code 0")
        cards = payload.get("results")
        if not isinstance(cards, list) or any(
            not isinstance(card, dict) or not isinstance(card.get("data"), dict)
            for card in cards
        ):
            raise RuntimeError("Expected results array with nested data objects")
    elif payload.get("message") != "success" or not isinstance(payload.get("data"), dict):
        raise RuntimeError("Video business status or data structure was unexpected")
    return payload


def candidate_ids(search_payload):
    # Use only after first_request("search", ...); this makes no requests.
    found = []
    for card in search_payload["results"]:
        data = card["data"]
        if data.get("template_key") == "Inner_EmptyContent":
            continue
        ids = [data.get(name) for name in ("group_id", "id_str")]
        valid = {value for value in ids if isinstance(value, str) and re.fullmatch(r"[0-9]+", value)}
        if len(valid) == 1:
            value = next(iter(valid))
            if value not in found:
                found.append(value)
    return found


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

For a known video, replace the final assignment with result = first_request("video", "7354954305222377999"); keep the field-list print. Do not append a second automatic request. This identifier is the public reference’s existing example, not a newly tested ID.

After a search, candidate_ids(result) is an optional local inspection step. It makes no network call and never reads the wrapper’s id. It considers only explicit numeric strings under results[].data.group_id or id_str, skips empty-content cards and rejects conflicting valid IDs. It deduplicates candidates without choosing one for another API request. An ID-shaped field is a candidate for review, not proof of relevance or current availability.

The helper returns the original business object without converting missing fields to zero or an empty “successful” record. An empty results array is accepted; a missing array or malformed nested data is rejected. These guards match the selected reference structure, not every possible upstream presentation state. Stop and inspect a changed structure instead of guessing another envelope.

Why the empty-content example matters

The full public saved search example dated 2026-10-07 uses the keyword 美食 (food). The following fragment preserves its relevant values while omitting tracking strings, executable presentation code and unrelated device metadata:

JSON
{
  "err_code": 0,
  "count": 10,
  "offset": 10,
  "has_more": true,
  "results": [
    {
      "id": "16b7eb80-0",
      "data": {"template_key": "Inner_EmptyContent"}
    }
  ]
}

That wrapper ID identifies a rendered card; it is not an explicit video ID under the nested data. The card says there is no matching content to use. The right outcome for this sample is no usable candidate, even though count is ten. Neither count nor list length alone establishes how many actual videos you obtained.

The short public README excerpt for another query stops before results. That clipping does not establish that results is absent from full responses. Conversely, a field table describing video cards does not guarantee every response contains one. Keep these two limits together when implementing a parser.

Do not execute card HTML, JavaScript, CSS or script strings to recover a missing ID. They are presentation material, not a substitute for validated data fields. If you later render highlighted text, treat it as untrusted markup and use an appropriate rendering/sanitization design; this tutorial does not render it or download anything.

Historical Xigua search-video parameter reference Historical search parameter screenshot. The current code requests offset zero explicitly; the screenshot does not prove ten videos, valid IDs or a newly tested next page.

The original search observation stays historical

The original tutorial recorded search run 07f62735-11c0-4394-997e-27da674651b9 on 2026-09-27 UTC. Its trimmed JSON is retained exactly below, including the illustrative placeholder. It is not the newer saved empty-card example and not a November business run:

JSON
{
  "id": "07f62735-11c0-4394-997e-27da674651b9",
  "status": "completed",
  "model": "xigua/app-v2/search-video",
  "outputs": [
    {
      "data": {
        "err_code": 0,
        "count": 10,
        "offset": 10,
        "has_more": true,
        "results": [ { "id": "…", "data": {} } ]
      }
    }
  ]
}

The old prose correctly noticed that each result nests its own payload, but its combined workflow relied on an undefined extract_item_id and then fetched detail and comments for every accepted entry. The replacement does not turn the placeholder into a working ID or imply that this historical excerpt proves a general extractor.

For pagination, the schema describes using the returned offset after the first page. This repair does not execute that continuation or establish an exhaustion rule. In particular, the saved empty-content response also has has_more: true; blindly looping on it would not answer whether useful videos exist. No automatic paging, fixed offset increment or retry is included.

What one-video actually checks

For the selected single-video route, the public README labels its example as a trimmed real response, but exposes no run date and provides no saved full example. We use it as a public reference, not a newly performed test. This minimal fragment keeps the shown status and three observed values:

JSON
{
  "message": "success",
  "data": {
    "danmaku_count": 36,
    "delete": 0,
    "digg_count": 42555
  }
}

The reference also describes author information, categories and related videos. Those fields are conditional data to inspect, not mandatory fields imposed by this helper. An empty inner data object passes only the reference’s outer structural check; it does not prove that a complete, available video record was returned. Preserve missing values and inspect explicit deletion or restriction flags when present.

Do not reuse search’s err_code check for this route. A completed SandBase run can still contain a provider failure, and accepting a missing error code as success would hide that failure. The helper checks exact message success and object shape instead. It does not assume an unrelated provider status field can override a failed message.

digg_count is an observed like counter, not a view count or engagement rate. A related-video link is not a transcript or a direct media download. The current route description promises less information than the older detail variant; the tutorial makes no title guarantee. Playback, transcription, comments or creator-history requests would require separately checked capabilities and authorization for the workload.

Keep the old endpoint change in its date

The 2026-10-01 article note recorded that the previously used xigua/app-v2/one-video-v2 was unavailable and substituted one-video based on schema review, without re-running that workflow. That is the historical reason for the substitution, not a fresh claim about the old route’s current availability. This repair selects the public one-video reference directly and still performs no business call.

Historical Xigua comments parameter reference Historical video-comment-list screenshot, retained with the original workflow evidence. Comments were not revalidated or called in this repair and are not a required follow-up to metadata.

Budget and failure handling

Both selected routes currently list $0.001 per request and eligibility for the organization’s shared 100-call daily quota across eligible APIs, resetting at 00:00 UTC. Eligibility is not the remaining allowance. This repair did not check balance, available quota or a charge and cannot promise a free successful execution.

One selected request lists at $0.001; independently choosing both would list at $0.002 before quota effects. The old workflow required one search plus two calls for each usable video, or 1 + 2N calls, before extra pages or retries. Because comments pricing was not rechecked here, this is request-count accounting, not a total-price quote for the old chain.

The helper separates HTTP errors, SandBase completion and endpoint-specific business status. Redirects, authentication/permission/budget errors, rate limits, invalid JSON and malformed envelopes stop execution. It does not automatically retry a timeout: the outcome may be unknown, and another request can increase usage. Error messages omit raw bodies, headers and keys.

Before expanding the workflow

Does count ten mean ten matching videos? No. The saved empty-content example demonstrates why the payload needs inspection. Review nested candidate fields rather than trusting an aggregate label.

Can I use results[0].id as item_id? No. It may be a card identifier. The optional local helper only considers documented nested ID fields, and a candidate still needs review before a separate request.

Will this return subtitles, a title or a download? This guide guarantees none of those. It validates one search page or the selected lightweight metadata response. Additional capabilities must be checked separately.

Where did the previous workflow go? Its code is preserved verbatim in the historical archive, with per-block hashes. It is evidence of the older implementation, not current runnable guidance. Start with one checked result, then use the Xigua API hub to investigate a specific next task.

Found this useful? Share it