浏览文档
示例
用 YouTube 视频 ID 获取标题、频道、时长及可用计数,保存为记录,并保留原始响应与用量。
本页内容
开始前准备
需要具有 youtube_metadata 权限的密钥和可用额度。选择 Python 3.10+ 与 requests,或 Bash、cURL 7.76+ 与 jq。Windows 的 Bash 版本请使用 Git Bash。
1. 选择一个视频
创建 video-metadata 文件夹,将 request.json 保存到其中,并在该文件夹打开终端。将 video_id 替换为观看 URL 或 YouTube 搜索结果中的 11 位 ID;不要传入完整 URL。
明确设置两个可选开关:首次请求不包含媒体格式和章节。此请求获取元数据,不下载视频或字幕。
{
"source": "youtube_metadata",
"video_id": "FUfGcZ092b0",
"params": {
"include_formats": false,
"include_chapters": false
}
}2. 获取并保存元数据
选择一种版本,将脚本保存到 request.json 旁。它读取 FLASHDATA_API_KEY,或通过隐藏输入提示获取密钥。智能体应从密钥存储加载该环境变量。
将 snapshot-001 作为输出文件夹运行。新文件夹发送一次元数据查询,并保存返回的用量。脚本确认响应成功、仅包含一个视频且 ID 与请求一致后,才写入 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. 读取视频记录
成功后输出 Saved <video ID> to snapshot-001/video.json。读取该文件查看完整元数据对象;record.json 包含实际提交的请求、requested_at 和用量。读取这些文件不调用 API。
python -m json.tool snapshot-001/video.json
python -m json.tool snapshot-001/record.jsoncat snapshot-001/video.json
cat snapshot-001/record.json输出示例
下方为精简的 video.json 示意,实际值会变化。脚本保留全部可用字段,包括 null 值,并将完整响应保存在 result.json。
{
"videoId": "FUfGcZ092b0",
"title": "Example research video",
"channel": "Example channel",
"duration": 120,
"viewCount": null,
"transcriptLanguages": [
"en"
]
}理解字段
| 字段 | 用途 |
|---|---|
| videoId | 记录的稳定主键。标题和频道显示名称可能变化。 |
| duration | 视频时长,单位为秒。缺失或 null 值保持为未知。 |
| viewCount / likeCount / commentCount | 本次快照中可用的计数。null 或缺失表示未知;零表示返回的实际计数。 |
| transcriptLanguages | 供独立字幕请求参考的候选语言代码。此列表不区分自动或人工字幕轨道。 |
复用快照或获取新快照
运行相同命令,可根据已保存响应重新生成 video.json 和 record.json,无需密钥或网络请求。编辑顶层 request.json 不会改变 snapshot-001 中保存的输入。
python metadata.py snapshot-001bash metadata.sh snapshot-001包含可用章节
需要章节标记时,用下方版本替换 request.json,并使用新的输出文件夹。include_chapters: true 返回已有章节,不会生成章节。省略时 include_chapters 和 include_formats 都默认为 true。
{
"source": "youtube_metadata",
"video_id": "FUfGcZ092b0",
"params": {
"include_formats": false,
"include_chapters": true
}
}python metadata.py snapshot-002bash metadata.sh snapshot-002元数据不可用时
| 遇到的情况 | 处理方法 |
|---|---|
| video_id 无效 | 仅使用 11 位 ID。输入校验会在发送请求前停止。 |
| 视频私有、已移除或受限 | 保留该 ID 的失败记录。检查来源错误,选择可访问的视频,避免反复提交同一项。 |
| 结果为空或 videoId 不匹配 | 脚本会停止,不写入 video.json。使用记录前检查保存的请求及响应。 |
| 计数、章节或语言缺失 | ID 匹配的元数据记录仍可能是成功结果。不可用字段保持未知,不填入编造的值。 |
| 401 / 403 / 402 | 分别检查密钥、youtube_metadata 权限和余额,再发起新尝试。 |
| 429 | 读取 response-headers.txt 中的 Retry-After 并等待。脚本不会自动重试。 |
| 超时、5xx、JSON 无效或文件夹不完整 | 保留本次尝试,再次提交前检查请求历史。复用其文件夹不会发送新请求。 |
将 inspect_metadata.py 保存到 metadata.py 旁,再运行。
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
done将视频用于工作流程
使用 videoId 将记录关联到搜索结果或数据集。需要口述内容时,下一步获取特定字幕轨道;处理多个 ID 时,使用视频补全指南。这些属于独立请求,需要对应权限并单独计费。