Skip to content
EN
Get API key
Browse documentation

Examples

YouTube Search API: Python Guide

Search YouTube by keyword, filter videos and build deduplicated CSV, JSONL and video-ID exports with Python.

On this page

Search YouTube with Python

Python SDK
python -m pip install -U flashdata
search.py
from flashdata import FlashData

with FlashData(api_key="your-flashdata-api-key") as client:
    result = client.youtube.search(
        "battery recycling process",
        max_results=5,
        filters={"type": "video"},
    )

for video in result["results"][0]["results"]:
    print(video["title"], video["videoId"])

A real search response

These are the first three of 20 results captured from the public demo for “battery recycling process” on 15 November 2026. The recording retains six fields per video. Run the live demo for fresh results.

results[0].results · 3 / 20
[
  {
    "videoId": "s2xrarUWVRQ",
    "title": "What *Really* happens to used Electric Car Batteries? - (you might be surprised)",
    "channel": "JerryRigEverything",
    "duration": 424,
    "viewCount": 5679251,
    "uploadDate": null
  },
  {
    "videoId": "RW0itbw_ALI",
    "title": "Recycling Batteries",
    "channel": "mbmmllc",
    "duration": 193,
    "viewCount": 91440,
    "uploadDate": null
  },
  {
    "videoId": "dyDoOcBMAHw",
    "title": "Why It's So Hard To Recycle Electric-Car Batteries | World Wide Waste",
    "channel": "Business Insider India",
    "duration": 376,
    "viewCount": 880172,
    "uploadDate": null
  }
]

Collect multiple searches into a dataset

The Python toolkit saves completed responses, removes duplicate video IDs and preserves each matching query and result position. Resume with the same options and resume=True to reuse completed searches.

Python toolkit
python -m pip install "https://github.com/flashdatadev/youtube-search-api/releases/download/v0.1.0/flashdata_youtube_search_api-0.1.0-py3-none-any.whl"
search_to_dataset.py
from flashdata_search import SearchClient, collect

with SearchClient(api_key="your-flashdata-api-key") as client:
    summary = collect(
        client,
        ["battery recycling process", "lithium battery recycling plant"],
        "output/batteries",
        max_results=20,
        filters={"duration": "4-20", "subtitles": True},
    )

print(summary["unique_videos"], "unique videos")
# output/batteries: videos.csv, videos.jsonl, video-ids.txt, summary.json

Standard or Extended Search?

Standard Search accepts 1–20 results per query. Extended Search accepts 1–700 at a separate rate. Both default to 20; max_results is a limit, not a guaranteed result count.

Use duration, upload date, sort order and subtitle filters to narrow discovery. These endpoints do not expose a page number or continuation token. Use Extended Search for a larger result set.

Retrieve more results with Extended Search
from flashdata import FlashData

with FlashData(api_key="your-flashdata-api-key") as client:
    result = client.youtube.search_extended(
        "battery recycling process",
        max_results=100,
        filters={"type": "video", "duration": "4-20"},
    )

print(len(result["results"][0]["results"]), "returned results")

Narrow the search when needed

filters
from flashdata import FlashData

with FlashData(api_key="your-flashdata-api-key") as client:
    result = client.youtube.search(
        "battery recycling process",
        max_results=20,
        filters={
            "type": "video",
            "duration": "4-20",
            "subtitles": True,
            "sort_by": "view_count",
        },
    )

Choose what to enrich next

Use video-ids.txt as the input to metadata, transcript or bulk download workflows. Review the candidate videos before selecting the IDs to enrich or deliver.

Your next taskUse the selected IDs for
Check a video's detailsFetch metadata for a selected ID. Inspect transcriptLanguages before requesting a specific caption track.
Summarize spoken contentRead an available transcript or caption track and cite timestamps. Do not summarize the video from its search description alone.
Enrich several videosUse selected-video-ids.txt as input to the enrichment guide. Metadata and captions are separate requests with their own permissions and charges.

Full REST example with saved responses

Optional: use requests or cURL directly. Save request.json beside the script. Put your API key in the Python key variable; the Bash version reads FLASHDATA_API_KEY or prompts for it. Each new output folder submits one search.

Run with search-001 as the output folder. A new folder submits one billable search; an existing folder is read locally. The script keeps the exact submitted request, response and usage.

youtube-search/request.json
{
  "source": "youtube_search",
  "query": "battery recycling process explained",
  "params": {
    "max_results": 5,
    "filters": {
      "type": "video"
    }
  }
}
Install in your Python environment
python -m pip install requests
youtube-search/search.py
import argparse
import json
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 search")
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_search"
            or not isinstance(request.get("query"), str) or not request["query"].strip()):
        raise SystemExit("request.json must contain youtube_search and a nonempty query")
    key = "your-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")
data = json.loads((out / "result.json").read_bytes())
if not isinstance(data, dict) or data.get("source") != "youtube_search" or data.get("status") != "done":
    raise SystemExit("Search did not finish successfully; inspect result.json")
pages = data.get("results")
if not isinstance(pages, list) or any(
    not isinstance(page, dict) or not isinstance(page.get("results"), list) for page in pages
):
    raise SystemExit("Expected results[].results arrays; inspect result.json")

videos, seen, skipped, duplicates = [], set(), 0, 0
for page in pages:
    for row in page["results"]:
        if not isinstance(row, dict):
            raise SystemExit("Expected video result objects; inspect result.json")
        video_id = row.get("videoId")
        if not isinstance(video_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id):
            skipped += 1
        elif video_id in seen:
            duplicates += 1
        else:
            seen.add(video_id)
            videos.append({**row, "url": "https://www.youtube.com/watch?v=" + video_id})
record = {
    "request": json.loads((out / "request.json").read_bytes()),
    "requested_at": (out / "requested-at.txt").read_text().strip(),
    "usage": data.get("usage"), "video_count": len(videos),
    "skipped_items": skipped, "duplicates_removed": duplicates, "result_file": "result.json",
}
for filename, value in (("videos.json", videos), ("record.json", record)):
    (out / filename).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
(out / "video-ids.txt").write_text("".join(v["videoId"] + "\n" for v in videos), encoding="utf-8")
print(f"Saved {len(videos)} videos to {out}/videos.json and video-ids.txt")
Run from youtube-search/
python search.py search-001

If the search needs attention

What happenedWhat to do
Fewer than five videos, or noneThis can be a successful search. Refine the query or remove a restrictive filter. totalResults describes this response, not the total number of matching YouTube videos.
401 / 403 / 402Check the key, youtube_search permission and balance, respectively. Fix the cause before creating a new attempt.
429For HTTP 429, wait for Retry-After. The toolkit retries only explicit 429 responses, at most twice by default, and stops if the requested delay exceeds 60 seconds. The direct SDK and REST examples do not retry automatically.
Timeout, 5xx or an incomplete folderKeep the saved files and check console History before submitting again. The toolkit will not automatically resubmit a request whose outcome is unknown.