Skip to content
EN
Get API key
Browse documentation

Examples

Retrieve timestamped captions

Save an existing YouTube caption track with its text, timing and language. Add a video link to each segment for citations in your app or agent's answer.

On this page

Before you start

Use a key with youtube_captions permission and available credits. Choose Python 3.10+ with requests, or Bash with cURL 7.76+ and jq. On Windows, use Git Bash for the Bash version.

1. Choose the video and caption track

Create a timestamped-captions folder and save request.json there. Open a terminal in that folder. Replace video_id with the video's 11-character ID, not its full URL.

This example requests English automatic captions. With auto=true, en tries en-orig first, then en. Explicit -orig codes and auto=false stay exact. The API never switches between automatic and uploader-provided captions.

timestamped-captions/request.json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": true
  }
}

2. Fetch and save the captions

Choose one version and save its script beside request.json. It reads FLASHDATA_API_KEY or asks for your key at a hidden prompt. Agents should load that environment variable from their secret store.

Run with track-001 as the output folder. A new folder sends one query and saves its reported usage. Before creating captions.json, the script verifies the returned video ID, language, caption origin and segment timings.

Install in your Python environment
python -m pip install requests
timestamped-captions/captions.py
import argparse
import getpass
import json
import math
import os
import re
from datetime import datetime, timezone
from pathlib import Path

import requests

parser = argparse.ArgumentParser()
parser.add_argument("folder", help="New output folder, or an existing saved caption request")
out = Path(parser.parse_args().folder)

if not out.exists():
    body = Path("request.json").read_bytes()
    request = json.loads(body)
    if (not isinstance(request, dict) or request.get("source") != "youtube_captions"
            or not isinstance(request.get("video_id"), str)
            or not re.fullmatch(r"[A-Za-z0-9_-]{11}", request["video_id"])):
        raise SystemExit("Use youtube_captions and an 11-character video_id")
    options = request.get("params")
    if (not isinstance(options, dict) or not isinstance(options.get("language"), str)
            or not re.fullmatch(r"[A-Za-z0-9-]{1,35}", options["language"])
            or type(options.get("auto")) is not bool):
        raise SystemExit("Set one language code and auto: true or false explicitly")
    key = os.environ.get("FLASHDATA_API_KEY") or getpass.getpass("FlashData API key: ")
    if not key.strip():
        raise SystemExit("An API key is required")
    out.mkdir()
    (out / "request.json").write_bytes(body)
    (out / "requested-at.txt").write_text(
        datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), encoding="utf-8"
    )
    try:
        response = requests.post(
            "https://data.flashdata.dev/v1/queries/realtime",
            headers={"X-API-Key": key, "Content-Type": "application/json",
                     "Accept": "application/json"},
            data=body, timeout=120, allow_redirects=False,
        )
    except requests.RequestException:
        raise SystemExit(f"Request interrupted. Keep {out} and check History before retrying.")
    (out / "result.json").write_bytes(response.content)
    (out / "response-headers.txt").write_text(
        "\n".join(f"{k}: {v}" for k, v in response.headers.items()), encoding="utf-8"
    )
    (out / "http-status.txt").write_text(str(response.status_code), encoding="utf-8")
else:
    print(f"Reading saved response from {out}; no API call.")

if not (out / "http-status.txt").exists():
    raise SystemExit("Incomplete attempt. Keep the folder and check History before retrying.")
status = (out / "http-status.txt").read_text().strip()
if status != "200":
    raise SystemExit(f"HTTP {status}: inspect {out}/result.json and response-headers.txt")
try:
    data = json.loads((out / "result.json").read_bytes())
except ValueError:
    raise SystemExit("Invalid JSON; inspect the saved result.json")
request = json.loads((out / "request.json").read_bytes())
if not isinstance(data, dict) or data.get("source") != "youtube_captions" or data.get("status") != "done":
    raise SystemExit("Caption request did not finish successfully; inspect result.json")
tracks = data.get("results")
if not isinstance(tracks, list) or len(tracks) != 1 or not isinstance(tracks[0], dict):
    raise SystemExit("Expected one caption track; inspect result.json")
track = tracks[0]
language = request["params"]["language"]
allowed_languages = [language]
if request["params"]["auto"] and not language.endswith("-orig"):
    allowed_languages.append(language + "-orig")
if (track.get("videoId") != request["video_id"]
        or track.get("languageCode") not in allowed_languages
        or track.get("requestedLanguageCode", track.get("languageCode")) != language
        or track.get("isAutoGenerated") is not request["params"]["auto"]):
    raise SystemExit("Returned video, language or caption origin does not match the request")
if not isinstance(track.get("segments"), list):
    raise SystemExit("Expected a segments array; inspect result.json")
segments = []
for cue in track["segments"]:
    if not isinstance(cue, dict):
        raise SystemExit("Expected caption segment objects")
    start, end, text = cue.get("start"), cue.get("end"), cue.get("text")
    if (type(start) not in (int, float) or not math.isfinite(start) or start < 0
            or type(end) not in (int, float) or not math.isfinite(end) or end < start
            or not isinstance(text, str)):
        raise SystemExit("Invalid caption timing or text; inspect result.json")
    segments.append({**cue, "url": f"https://www.youtube.com/watch?v={track['videoId']}&t={math.floor(start)}s"})
captions = {**track, "segments": segments}
record = {"request": request, "requested_at": (out / "requested-at.txt").read_text().strip(),
          "usage": data.get("usage"), "segment_count": len(segments), "result_file": "result.json"}
for filename, value in (("captions.json", captions), ("record.json", record)):
    (out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Saved {len(segments)} segments to {out}/captions.json")
if not any(cue["text"].strip() for cue in segments):
    print("No caption text to cite. Keep the empty track and report the gap.")
Run from timestamped-captions/
python captions.py track-001

3. Read the timestamped text

Success prints Saved N segments to track-001/captions.json. That file preserves the returned track and adds a URL to each segment. record.json contains the exact submitted request, requested_at, usage and segment_count; result.json keeps the original API response.

Read locally · no API call
python -m json.tool track-001/captions.json
python -m json.tool track-001/record.json

Example output

Abbreviated, illustrative captions.json. Your text and timing will differ. languageName may be null; the script keeps it that way.

timestamped-captions/track-001/captions.json
{
  "videoId": "FUfGcZ092b0",
  "languageCode": "en",
  "languageName": null,
  "isAutoGenerated": true,
  "segments": [
    {
      "start": 12.5,
      "end": 16.2,
      "text": "This is an illustrative caption segment.",
      "url": "https://www.youtube.com/watch?v=FUfGcZ092b0&t=12s"
    }
  ]
}

Cite a video passage

Print the first three segments with their source links. start and end stay in seconds with their original precision. Only the URL's start time is rounded down: 12.5 seconds becomes &t=12s. Segment order and overlapping timings are preserved.

Save cite.py beside captions.py, then run it from the same folder.

timestamped-captions/cite.py
import json
from pathlib import Path

captions = json.loads(Path("track-001/captions.json").read_text(encoding="utf-8"))
for cue in captions["segments"][:3]:
    print(f"[{cue['start']}–{cue['end']}s] {cue['text']}")
    print(cue["url"])
    print()
Print citations from saved captions
python cite.py

Keep the caption context

Use segment text as the evidence for a citation; fullText is useful for reading but does not locate a passage. Check surrounding segments before quoting, especially for automatic captions. Retain languageCode and isAutoGenerated so your app or agent can identify the source track.

Reuse the saved track

Run the same command to rebuild captions.json from the saved response, without a key or new query. Editing the top-level request.json does not change the request stored with track-001.

Reuse locally
python captions.py track-001

Choose another track

To request uploader-provided English captions, replace request.json with this version and use track-002. Change language only to the code you intend to retrieve, such as en-orig or zh-Hans. Metadata's transcriptLanguages lists candidate codes, not whether each one has an automatic or uploaded track.

The script expects one language string. Language arrays have a different response shape with tracks and per-language errors; use the API reference for that workflow.

timestamped-captions/request.json
{
  "source": "youtube_captions",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": false
  }
}
New track · another API request
python captions.py track-002

If captions are missing or unusable

What happenedWhat to do
The selected track is unavailableCheck the video, language and auto selection. Choose an available track explicitly; repeating the same request will not create captions.
segments: []An existing track can contain no text. The script saves the empty track and reports the gap. Do not turn it into a transcript or summary.
Wrong video, language or caption originNo captions.json is written. Compare the saved request with result.json before using any text.
Invalid timings or missing segmentsInspect result.json. The script stops instead of assigning invented timestamps or silently dropping a bad segment.
401 / 403 / 402Check the key, youtube_captions permission and balance, respectively, before a new attempt.
429Read Retry-After in response-headers.txt and wait. The script does not retry automatically.
Timeout, 5xx, invalid JSON or an incomplete folderKeep the attempt and check History before submitting again. Reusing its folder never sends another query.

Save inspect_captions.py beside captions.py, then run it.

timestamped-captions/inspect_captions.py
from pathlib import Path

for name in ("http-status.txt", "response-headers.txt", "result.json"):
    path = Path("track-001") / name
    print(f"--- {name} ---")
    print(path.read_text(encoding="utf-8", errors="replace") if path.exists() else "Not saved")
Inspect locally
python inspect_captions.py