Browse documentation
Examples
Turn a YouTube video ID into a saved record of its title, channel, duration and available counts. Keep the original response and usage alongside it.
On this page
Before you start
Use a key with youtube_metadata 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 one video
Create a video-metadata folder and save request.json there. Open a terminal in that folder. Replace video_id with the 11-character ID from a watch URL or a YouTube Search result; do not pass the full URL.
Set both optional flags explicitly: this first request omits media formats and chapters. It retrieves metadata without downloading the video or its captions.
{
"source": "youtube_metadata",
"video_id": "FUfGcZ092b0",
"params": {
"include_formats": false,
"include_chapters": false
}
}2. Fetch and save the metadata
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 snapshot-001 as the output folder. A new folder sends one metadata query and saves its reported usage. The script checks for a successful response containing exactly one video with the requested ID before writing video.json.
python -m pip install requestsimport argparse
import getpass
import json
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 snapshot")
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_metadata"
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_metadata and an 11-character video_id, not a URL")
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_metadata" or data.get("status") != "done":
raise SystemExit("Metadata request did not finish successfully; inspect result.json")
videos = data.get("results")
if (not isinstance(videos, list) or len(videos) != 1 or not isinstance(videos[0], dict)
or videos[0].get("videoId") != request["video_id"]):
raise SystemExit("Expected one metadata object matching the requested video_id")
record = {
"request": request,
"requested_at": (out / "requested-at.txt").read_text().strip(),
"usage": data.get("usage"), "result_file": "result.json",
}
for filename, value in (("video.json", videos[0]), ("record.json", record)):
(out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Saved {videos[0]['videoId']} to {out}/video.json")
python metadata.py snapshot-001curl --version
jq --version#!/usr/bin/env bash
set -euo pipefail
out="${1:?Usage: bash metadata.sh OUTPUT_FOLDER}"
if [[ ! -e "$out" ]]; then
jq -e '.source == "youtube_metadata" and
(.video_id | if type == "string" then length == 11 and test("^[A-Za-z0-9_-]{11}$")
else false end)' request.json > /dev/null
if [[ -z "${FLASHDATA_API_KEY:-}" ]]; then
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
fi
: "${FLASHDATA_API_KEY:?An API key is required}"
mkdir -- "$out"
cp request.json "$out/request.json"
date -u +'%Y-%m-%dT%H:%M:%SZ' > "$out/requested-at.txt"
curl --fail-with-body --silent --show-error --max-time 120 \
--request POST 'https://data.flashdata.dev/v1/queries/realtime' \
--header "X-API-Key: $FLASHDATA_API_KEY" \
--header 'Content-Type: application/json' --header 'Accept: application/json' \
--data-binary "@$out/request.json" \
--dump-header "$out/response-headers.txt" --output "$out/result.json" \
--write-out '%{http_code}' > "$out/http-status.txt" || {
printf 'Request failed. Keep %s and inspect its saved files before retrying.\n' "$out" >&2
exit 1
}
else
printf 'Reading saved response from %s; no API call.\n' "$out"
fi
if [[ ! -f "$out/http-status.txt" ]] || [[ "$(cat "$out/http-status.txt")" != 200 ]]; then
printf 'Incomplete or failed attempt. Inspect the saved files and History before retrying.\n' >&2
exit 1
fi
video=$(jq -e --slurpfile request "$out/request.json" '
if .source != "youtube_metadata" or .status != "done"
then error("Expected a successful youtube_metadata response") else . end
| .results
| if type != "array" then error("Expected a metadata array")
elif length != 1 then error("Expected exactly one video") else .[0] end
| if type != "object" then error("Expected a metadata object")
elif .videoId != $request[0].video_id then error("Returned videoId does not match the request")
else . end' "$out/result.json")
printf '%s\n' "$video" > "$out/video.json"
jq --slurpfile request "$out/request.json" \
--arg requested_at "$(tr -d '\r\n' < "$out/requested-at.txt")" \
'{request: $request[0], requested_at: $requested_at, usage, result_file: "result.json"}' \
"$out/result.json" > "$out/record.json"
printf 'Saved %s to %s/video.json\n' "$(jq -r .videoId "$out/video.json")" "$out"
bash metadata.sh snapshot-0013. Read the video record
Success prints Saved <video ID> to snapshot-001/video.json. Read that file for the full metadata object and record.json for the exact submitted request, requested_at and usage. Reading these files makes no API call.
python -m json.tool snapshot-001/video.json
python -m json.tool snapshot-001/record.jsoncat snapshot-001/video.json
cat snapshot-001/record.jsonExample output
Abbreviated, illustrative video.json. Returned values vary. The script preserves every available field, including null values, and keeps the complete response in result.json.
{
"videoId": "FUfGcZ092b0",
"title": "Example research video",
"channel": "Example channel",
"duration": 120,
"viewCount": null,
"transcriptLanguages": [
"en"
]
}Read the fields
| Field | Use it for |
|---|---|
| videoId | The record's stable key. Title and channel display names can change. |
| duration | Video length in seconds. Preserve missing or null values as unknown. |
| viewCount / likeCount / commentCount | Counts available in this snapshot. Null or missing is unknown; zero is a reported count. |
| transcriptLanguages | Candidate language codes for a separate caption request. This list does not identify whether a track is automatic or manual. |
Reuse the snapshot or request another
Run the same command to rebuild video.json and record.json from the saved response. No key or network request is needed. Editing the top-level request.json does not change the input stored with snapshot-001.
python metadata.py snapshot-001bash metadata.sh snapshot-001Include available chapters
To include chapter markers, replace request.json with this version and use a new output folder. include_chapters: true returns chapters when available; it does not create them. Both include_chapters and include_formats default to true when omitted.
{
"source": "youtube_metadata",
"video_id": "FUfGcZ092b0",
"params": {
"include_formats": false,
"include_chapters": true
}
}python metadata.py snapshot-002bash metadata.sh snapshot-002If metadata is unavailable
| What happened | What to do |
|---|---|
| Invalid video_id | Use only the 11-character ID. Input validation stops before sending the request. |
| Private, removed or restricted video | Keep the failure for that ID. Check the source error and choose an accessible video instead of repeatedly submitting the same item. |
| Empty result or a different videoId | The script stops without writing video.json. Inspect the saved request and response before using the record. |
| Missing counts, chapters or languages | A matching metadata record can still be successful. Preserve unavailable fields as unknown; do not fill them with invented values. |
| 401 / 403 / 402 | Check the key, youtube_metadata permission and balance, respectively, before a new attempt. |
| 429 | Read Retry-After in response-headers.txt and wait. The script never retries automatically. |
| Timeout, 5xx, invalid JSON or an incomplete folder | Keep the attempt and check History before submitting again. Reusing its folder makes no new request. |
Save inspect_metadata.py beside metadata.py, then run it.
from pathlib import Path
for name in ("http-status.txt", "response-headers.txt", "result.json"):
path = Path("snapshot-001") / name
print(f"--- {name} ---")
print(path.read_text(encoding="utf-8", errors="replace") if path.exists() else "Not saved")python inspect_metadata.pyfor name in http-status.txt response-headers.txt result.json; do
printf '\n--- %s ---\n' "$name"
if [[ -f "snapshot-001/$name" ]]; then cat "snapshot-001/$name"; else printf 'Not saved\n'; fi
doneUse the video in your workflow
Use videoId to join this record to your search results or dataset. For spoken content, retrieve a specific caption track next. For several IDs, use the enrichment guide. These are separate requests with their own permissions and charges.