How to Build a YouTube Transcript Pipeline with One API | SandBase
Build a YouTube transcript workflow in Python: discover caption tracks, select a language, retrieve caption content, and save SRT for research.

A list of caption languages is not yet a transcript you can summarize. This guide is for Python developers moving from a YouTube channel to captions for research: resolve the channel, find a video, inspect its tracks, then request a selected language and save its content. If you already have a video ID or URL, start at the captions step. SandBase requests use a Bearer key; keep it on the server.
Tested November 5, 2026 (UTC), through the HTTP Model API. The NASA channel resolved to UCLA_DiR1FfKNvjuUpBHmylQ. The first listing contained 30 videos; its first video, Zezt6EsG9WE, returned 20 caption languages. Selecting en with format=srt returned 160 timed cues, saved and read back unchanged as UTF-8. These are one run’s observations, not fixed page sizes or availability guarantees. The code below uses the field paths observed in those responses and stops when required data is missing.
If you want the full endpoint tour first, start with the YouTube public data API hub. This piece is the applied pipeline.
Key takeaway
- Channel discovery:
channel-id→channel-videos→video-info→video-captions; retrieving a selected track needs another captions request.- Every call is
POST /v1/api/youtube/<path>with oneSANDBASE_API_KEY; responses share the{ id, status, model, outputs }envelope.- Carry the
channel_idand eachvideo_idforward as stable keys between steps.- Public, read-only captions only; you still need a SandBase key, but no Google Cloud project or OAuth on your side.
The pipeline at a glance
| Step | Endpoint | Input | You get |
|---|---|---|---|
| 1. Resolve channel | youtube/web/channel-id | channel_name | a stable channel_id |
| 2. List videos | youtube/web-v2/channel-videos | channel_id | video listing; inspect continuation details |
| 3. Read video | youtube/web-v2/video-info | video_id | video metadata; inspect caption information |
| 4. Discover tracks | youtube/web-v2/video-captions | video_id or video_url, no language | available caption languages |
| 5. Retrieve content | same captions endpoint | video input, selected language_code, format=srt | caption content in SRT format |
Existing channel-videos reference screenshot showing request parameters. Its empty example payload does not verify a business-field mapping.
Step 1 — Resolve the channel
You usually start with a human-facing name, not an id. Turn it into a stable channel_id once, then reuse it. Install requests with python -m pip install requests and set SANDBASE_API_KEY in your environment. Run the blocks in order using Python 3.10+. They use the Model API POST route; they are not catalog GET requests:
import os
import requests
BASE = "https://api.sandbase.ai/v1/api/youtube"
HEADERS = {
"Authorization": f"Bearer {os.environ['SANDBASE_API_KEY']}",
"Content-Type": "application/json",
}
def call(path: str, payload: dict) -> dict | list:
resp = requests.post(f"{BASE}/{path}", headers=HEADERS, json=payload, timeout=120)
resp.raise_for_status()
body = resp.json()
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("Completed response has no valid outputs array")
data = outputs[0].get("data")
if not isinstance(data, (dict, list)):
raise RuntimeError("Completed response has no data object or array")
return data
channel = call("web/channel-id", {"channel_name": "NASA"})
if not isinstance(channel, dict) or not channel.get("channel_id"):
raise ValueError("Channel response has no channel_id")
channel_id = channel["channel_id"]
print(channel_id)The call helper branches on status before touching outputs — reuse it for every step below. The envelope parser rejects missing data instead of silently returning an empty object. The following checks cover the shapes observed in this test; treat a changed shape as an integration error rather than empty data.
Step 2 — List the channel’s videos
Pass the channel_id to list recent uploads. The tested response put records in videos and the next-page value in continuation_token:
listing = call("web-v2/channel-videos", {"channel_id": channel_id})
if not isinstance(listing, dict) or not isinstance(listing.get("videos"), list):
raise ValueError("Channel listing has no videos array")
videos = [v for v in listing["videos"] if isinstance(v, dict) and v.get("video_id")]
if not videos:
raise ValueError("Channel listing contains no usable video IDs")
first = videos[0]
print(first.get("video_id"), "-", first.get("title"))In this test, a second request with the returned continuation_token and the same channel_id returned another 30 videos. The two pages had no overlapping video IDs. That verifies a next-page handoff, not complete channel history. Keep a page/call budget, deduplicate by video ID, and stop on an absent or repeated token; do not loop indefinitely.
Step 3 — Read the video’s metadata
Before pulling captions, inspect the video metadata for your record:
info = call("web-v2/video-info", {"video_id": first.get("video_id")})
if not isinstance(info, dict):
raise ValueError("Video metadata is not an object")
print(info.get("title"), "|", info.get("author"), "|", info.get("category"))
print(info.get("view_count"), "views,", info.get("length_seconds"), "seconds")The tested metadata included title, author, category, view_count, length_seconds and captions. Some counts were strings, so normalize types before doing arithmetic. Metadata does not guarantee that a later caption download will succeed; the next request checks the tracks directly.
Historical video-info reference screenshot; it is not a screenshot of the live test described above.
Step 4 — Discover caption tracks
Request the available tracks for the video without a language_code. In this continuation of the channel example, first verify that the video ID mapping produced a value:
video_id = first.get("video_id")
if not video_id:
raise ValueError("Select a video ID before requesting captions")
result = call("web-v2/video-captions", {"video_id": video_id})
if not isinstance(result, dict) or not isinstance(result.get("captions"), list):
raise ValueError("Caption discovery has no captions array")
languages = [t["language_code"] for t in result["captions"]
if isinstance(t, dict) and isinstance(t.get("language_code"), str) and t["language_code"]]
if not languages:
raise ValueError("No caption tracks were returned")
print(languages)This response is a language-selection step, not the transcript body. The tested discovery payload was an object with captions and video_id; each retained track had a language_code and language_name. Inspect the printed codes before selecting a language. Do not assume another video will offer English or an automatic track.
Existing video-captions reference screenshot. Use the current reference below for language selection and caption-content retrieval; its old generated request omits video input, so use the current reference rather than copying that request.
Get transcript content after selecting a caption language
The first caption request discovers the tracks available for a video; it does not finish the transcript pipeline. Provide a video_id or video_url, then leave language_code empty to discover available tracks. Select a language code returned for that video and make another request with that code to retrieve the caption content. Use the same video input in both requests. A language code from a different video is not evidence that this video offers it.
Use the YouTube captions API reference for the current request contract and Playground. Its README describes content as the selected-format caption body under outputs[0].data. The save function below checks the requested identity, language, format and non-empty content before writing. The parameter table marks the two video identifiers individually optional; the README still requires a video ID or URL.
The next block deliberately requests English only if it appeared in this video’s discovery response. Change the language explicitly instead of silently substituting another one:
language_code = "en"
if language_code not in languages:
raise ValueError("Choose a language_code from the printed available tracks")
caption = call("web-v2/video-captions", {
"video_id": video_id,
"language_code": language_code,
"format": "srt",
})The captions endpoint offers two distinct operations through the same route: discover the available languages, then fetch the chosen track. Count both requests when planning a collection job and check current pricing in the reference. A returned language list must never be sent to a summarizer as though it contained the spoken words.
Save SRT captions and pass them to a research task
Set format to srt when you need a subtitle file with start and end timestamps. After the selected-language request completes, check that the returned content is a non-empty string. Save that string as a UTF-8 .srt file, preserving cue numbers, timing lines and blank lines. Do not write the entire JSON response to an SRT file or treat the track-discovery response as transcript text.
This function saves the original content plus a separate provenance record. The timing-line check detects obvious wrong output; it is not a complete SRT validator. Re-running for the same video and language replaces the previous files in captions/.
import json
import re
from datetime import datetime, timezone
from pathlib import Path
def save_srt(data: dict, video_id: str, language_code: str, directory: Path) -> Path:
if not isinstance(data, dict):
raise ValueError("Caption result is not an object")
if (data.get("video_id") != video_id or data.get("language_code") != language_code
or data.get("format") != "srt"):
raise ValueError("Caption result does not match the requested video, language and format")
content = data.get("content")
if not isinstance(content, str) or not content.strip():
raise ValueError("Caption content is empty or missing")
if not re.search(r"^\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3}", content, re.M):
raise ValueError("Caption content has no SRT timing line")
if not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id) or not re.fullmatch(r"[A-Za-z0-9.-]+", language_code):
raise ValueError("Unsafe output filename")
directory.mkdir(parents=True, exist_ok=True)
path = directory / f"{video_id}.{language_code}.srt"
path.write_text(content, encoding="utf-8")
path.with_suffix(".source.json").write_text(json.dumps({
"video_id": video_id,
"source_url": f"https://www.youtube.com/watch?v={video_id}",
"language_code": language_code,
"format": "srt",
"retrieved_at": datetime.now(timezone.utc).isoformat(),
}, ensure_ascii=False, indent=2), encoding="utf-8")
return path
saved = save_srt(caption, video_id, language_code, Path("captions"))
print(saved)Keep the source video URL and selected language alongside the file so that later research can trace statements back to the video. Record the retrieval date separately from the video’s publication date. Preserve the original SRT if you also create plain text for an LLM: flattening the text loses the timing needed to inspect a quotation in context.
The YouTube Research Skill declares the captions endpoint as a dependency and asks for timestamps when available. After retrieving captions, use that task connection to organize a research brief with source links. Installation and MCP configuration are separate steps explained on the Skill page; this article does not demonstrate an executed Skill run or an automatic SRT-upload integration.
Connect retrieval to indexing
Saving SRT is not the same as indexing it. The tested path ends with a subtitle file and a provenance record. Connect those saved materials to your own indexer only after deciding how it should represent cue timing and video sources.
For each video, track whether discovery completed, a usable language was selected, and non-empty caption content was saved. Only then pass the saved material to your own indexer. Keep missing-caption cases separate from request errors so that a failed fetch does not become an apparently empty document. The indexing and summarization stages remain application work, not behavior supplied by the snippets above.
Handling the rough edges
- Handle missing tracks. The code stops on an empty track list. Our sampled videos had captions, so this empty-list branch is covered by offline tests rather than a confirmed live no-caption sample. A failed request is not proof that captions are absent.
- Page deliberately. Check the current channel endpoint reference and response before wiring a continuation value. Do not assume the first page is the whole channel or invent a token path.
- Branch on
status. Thecallhelper rejects non-completed responses and malformedoutputs, including errors without a structured message. - Separate errors from empty results. Missing video input and an invalid language each returned HTTP 400 in this test. The helper raises instead of saving an empty transcript. Handle HTTP 429 with bounded backoff in production; no rate-limit response was induced during testing.
- Read the schema. Field names and nesting can differ by endpoint version — inspect one real response and map paths before you build.
What the shared API layer changes
Using one Bearer-authenticated HTTP helper keeps request handling in one place. You still need to inspect each endpoint’s business payload and map it into your own records. A shared response envelope does not make the channel listing, video metadata and captions payloads identical.
The trade-off is that your application reads public data through SandBase rather than controlling the underlying fetch. Caption availability and upstream access can change. Keep the original sources and retrieval states so that research can distinguish missing material from a successful fetch, and revisit the current reference when a field mapping stops working.
FAQ
Do I need a Google account or OAuth?
No. You authenticate to SandBase with your SANDBASE_API_KEY. This pipeline reads public, read-only captions and needs no Google Cloud project, YouTube Data API quota, or OAuth on your side.
How do I page through a channel’s videos?
The test passed the first response’s continuation_token back to channel-videos with the same channel ID and received a second page. Stop when no new token or records are returned, and set a call budget. Two pages do not establish complete channel history.
Does video-captions return the transcript text?
Without language_code, it lists available caption tracks. With a language code returned for that video, it retrieves caption content in the selected format. Discover the tracks first; do not assume that every video has captions or that a particular language is available.
Can this retrieve a transcript when no caption track exists? This workflow uses existing caption tracks on accessible public videos. It does not promise audio transcription for videos without captions, private-video access, or access-limit bypasses. Treat missing captions as an incomplete input for the research task, not as transcript text.
Observed HTTP response excerpt
For POST /v1/api/youtube/web-v2/video-captions with {"video_id":"Zezt6EsG9WE","language_code":"en","format":"srt"}, run 6884d7cd-e433-4cd5-8ef1-db0854cc30bf returned this trimmed payload on November 5, 2026. Only the first cue is retained; the full result had 160 cues.
{"id":"6884d7cd-e433-4cd5-8ef1-db0854cc30bf","status":"completed","outputs":[{"data":{"video_id":"Zezt6EsG9WE","language_code":"en","format":"srt","content":"1\n00:00:02,135 --> 00:00:03,069\nThink about"}}]}The video_url alternative also returned the same available language codes in a separate discovery request. Missing video input and language_code=zz-invalid were rejected; these observations are not a complete catalog of error responses. Private videos, ASR, XML/JSON3/TXT output, automatic retries and executed Skill research were not tested here.
Next steps
Start with one accessible public video and inspect its available languages in the captions reference. Retrieve the selected track, save the SRT with its source information, and verify a timestamp before connecting your indexer or research task. Expand to channel collection only after those stages work with your own responses.
Found this useful? Share it