Skip to content
EN
Get API key
Browse documentation

Examples

Retrieve one video's metadata

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.

video-metadata/request.json
{
  "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.

Install in your Python environment
python -m pip install requests
video-metadata/metadata.py
import 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")
Run from video-metadata/
python metadata.py snapshot-001

3. 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.

Read locally
python -m json.tool snapshot-001/video.json
python -m json.tool snapshot-001/record.json

Example 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.

video-metadata/snapshot-001/video.json
{
  "videoId": "FUfGcZ092b0",
  "title": "Example research video",
  "channel": "Example channel",
  "duration": 120,
  "viewCount": null,
  "transcriptLanguages": [
    "en"
  ]
}

Read the fields

FieldUse it for
videoIdThe record's stable key. Title and channel display names can change.
durationVideo length in seconds. Preserve missing or null values as unknown.
viewCount / likeCount / commentCountCounts available in this snapshot. Null or missing is unknown; zero is a reported count.
transcriptLanguagesCandidate 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.

Reuse saved data
python metadata.py snapshot-001

Include 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.

video-metadata/request.json
{
  "source": "youtube_metadata",
  "video_id": "FUfGcZ092b0",
  "params": {
    "include_formats": false,
    "include_chapters": true
  }
}
Request another snapshot
python metadata.py snapshot-002

If metadata is unavailable

What happenedWhat to do
Invalid video_idUse only the 11-character ID. Input validation stops before sending the request.
Private, removed or restricted videoKeep 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 videoIdThe script stops without writing video.json. Inspect the saved request and response before using the record.
Missing counts, chapters or languagesA matching metadata record can still be successful. Preserve unavailable fields as unknown; do not fill them with invented values.
401 / 403 / 402Check the key, youtube_metadata permission and balance, respectively, before a new attempt.
429Read Retry-After in response-headers.txt and wait. The script never retries automatically.
Timeout, 5xx, invalid JSON or an incomplete folderKeep 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.

video-metadata/inspect_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")
Inspect locally
python inspect_metadata.py

Use 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.