# YouTube Search API: Python गाइड

Python से YouTube पर कीवर्ड खोजें, वीडियो फ़िल्टर करें और बिना डुप्लिकेट वाले CSV, JSONL तथा वीडियो ID निर्यात करें।

कैनोनिकल संदर्भ: https://flashdata.dev/hi/docs/guides/youtube-search-recipe
समीक्षित: 2026-11-16 द्वारा FlashData

<a id="quickstart"></a>

## Python से YouTube खोजें

### Python SDK

```bash
python -m pip install -U flashdata
```

### search.py

```python
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"])
```

- [API कुंजी लें](https://flashdata.dev/signup)
- [लाइव खोज आज़माएँ](https://flashdata.dev/hi/products/youtube-data#playground)

<a id="recorded-response"></a>

## वास्तविक खोज प्रतिक्रिया

ये 15 नवंबर 2026 को सार्वजनिक डेमो में “battery recycling process” के लिए मिले 20 परिणामों में से पहले तीन हैं। रिकॉर्डिंग में प्रति वीडियो छह फ़ील्ड हैं। नए परिणामों के लिए लाइव डेमो चलाएँ।

### results[0].results · 3 / 20

```json
[
  {
    "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
  }
]
```

- [वास्तविक खोज प्रतिक्रिया](https://github.com/flashdatadev/youtube-search-api/blob/main/src/flashdata_search/recorded/search.json)

<a id="collection"></a>

## कई खोजों को एक डेटासेट में इकट्ठा करें

Python टूलकिट पूरी हुई प्रतिक्रियाएँ सहेजता है, डुप्लिकेट वीडियो ID हटाता है और हर मिलती क्वेरी व परिणाम की स्थिति रखता है। पूरी खोजों का दोबारा उपयोग करने के लिए उन्हीं विकल्पों और resume=True के साथ जारी रखें।

### Python toolkit

```bash
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

```python
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
```

- [YouTube Search API Python टूलकिट](https://github.com/flashdatadev/youtube-search-api)

<a id="extended"></a>

## मानक या विस्तृत खोज?

मानक खोज प्रति क्वेरी 1–20 परिणाम स्वीकार करती है। विस्तृत खोज अलग दर पर 1–700 स्वीकार करती है। दोनों का डिफ़ॉल्ट 20 है; max_results एक सीमा है, परिणामों की गारंटीकृत संख्या नहीं।

अवधि, अपलोड की तारीख, क्रम और उपशीर्षक फ़िल्टर से खोज सीमित करें। ये एंडपॉइंट पृष्ठ संख्या या continuation token नहीं देते। अधिक परिणामों के लिए विस्तृत खोज चुनें।

### विस्तृत खोज से अधिक परिणाम पाएँ

```python
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")
```

- [विस्तारित खोज का उपयोग कब करें](https://flashdata.dev/hi/docs/sources/youtube_search_extended/reference.md)
- [खोज की कीमतें तुलना करें](https://flashdata.dev/hi/products/youtube-data#choose-api)

<a id="filters"></a>

## जब आवश्यक हो तो खोज संकीर्ण करें

### filters

```python
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",
        },
    )
```

- [सभी खोज फिल्टर](https://flashdata.dev/hi/docs/sources/youtube_search/reference.md#parameters)

<a id="select"></a>

## अगले को समृद्ध करने के लिए क्या चुनें

video-ids.txt को मेटाडेटा, ट्रांसक्रिप्ट या बल्क डाउनलोड वर्कफ़्लो का इनपुट बनाएँ। जानकारी जोड़ने या डिलीवर करने के लिए ID चुनने से पहले संभावित वीडियो देखें।

| आपका अगला कार्य | चयनित IDs के लिए उपयोग करें |
| --- | --- |
| एक वीडियो का विवरण चेक करें | एक चयनित ID के लिए मेटाडाटा लें। एक विशिष्ट कैप्शन ट्रैक का अनुरोध करने से पहले transcriptLanguages का निरीक्षण करें। |
| बोली जाने वाली सामग्री को सारांशित करें | एक उपलब्ध ट्रांसक्रिप्ट या कैप्शन ट्रैक और साइट टाइमस्टैम्प पढ़ें। वीडियो को अकेले अपने खोज विवरण से सारांशित न करें। |
| कई वीडियो | उपयोग selected-video-ids.txt संवर्धन गाइड के लिए इनपुट के रूप में। मेटाडाटा और कैप्शन अपनी अनुमति और शुल्क के साथ अलग-अलग अनुरोध हैं। |

- [एक वीडियो का मेटाडाटा](https://flashdata.dev/hi/docs/guides/video-metadata-recipe/reference.md)
- [उद्धरण के साथ एक वीडियो को संक्षेप में प्रस्तुत करें](https://flashdata.dev/hi/docs/guides/youtube-summary/reference.md)
- [एनरिक चयनित वीडियो IDs](https://flashdata.dev/hi/docs/guides/enrich-youtube-videos/reference.md)
- [Bulk API](https://flashdata.dev/hi/docs/reference/bulk-processing/reference.md?source=youtube_download#playground)

<a id="rest"></a>

## प्रतिक्रियाएँ सहेजने वाला पूरा REST उदाहरण

वैकल्पिक: requests या cURL सीधे इस्तेमाल करें। request.json को स्क्रिप्ट के पास रखें। Python के key वेरिएबल में API कुंजी डालें; Bash, FLASHDATA_API_KEY पढ़ता है या कुंजी माँगता है। हर नया आउटपुट फ़ोल्डर एक खोज भेजता है।

खोज-001 के साथ आउटपुट फ़ोल्डर के रूप में चलाएं। एक नया फ़ोल्डर एक बिलेबल खोज प्रस्तुत करता है; एक मौजूदा फ़ोल्डर स्थानीय रूप से पढ़ा जाता है। स्क्रिप्ट सटीक जमा अनुरोध, प्रतिक्रिया और उपयोग रखता है।

### youtube-search/request.json

```json
{
  "source": "youtube_search",
  "query": "battery recycling process explained",
  "params": {
    "max_results": 5,
    "filters": {
      "type": "video"
    }
  }
}
```

### Python

#### अपने Python वातावरण में स्थापित करें

```bash
python -m pip install requests
```

#### youtube-search/search.py

```python
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")
```

#### यूट्यूब खोज से भागो/

```bash
python search.py search-001
```


### Bash

#### अपने उपकरण की जाँच करें

```bash
curl --version
jq --version
```

#### youtube-search/search.sh

```bash
#!/usr/bin/env bash
set -euo pipefail
out="${1:?Usage: bash search.sh OUTPUT_FOLDER}"

if [[ ! -e "$out" ]]; then
  jq -e '.source == "youtube_search" and
    (.query | if type == "string" then test("\\S") 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
selection=$(jq -e '
  if .source != "youtube_search" or .status != "done" or (.results | type) != "array"
  then error("Expected a successful youtube_search response") else . end
  | [.results[] | if (.results | type) != "array"
      then error("Expected a video list") else .results[] end
      | if type != "object" then error("Expected video result objects") else . end]
  | reduce .[] as $row ({seen: {}, videos: [], skipped: 0, duplicates: 0};
      if ($row.videoId | if type == "string" then length == 11 and test("^[A-Za-z0-9_-]{11}$") else false end) == false
      then .skipped += 1
      elif .seen[$row.videoId] then .duplicates += 1
      else .seen[$row.videoId] = true
        | .videos += [$row + {url: ("https://www.youtube.com/watch?v=" + $row.videoId)}] end)
  | del(.seen)' "$out/result.json")
printf '%s' "$selection" | jq '.videos' > "$out/videos.json"
jq -r '.[].videoId' "$out/videos.json" > "$out/video-ids.txt"
jq --slurpfile request "$out/request.json" --argjson selection "$selection" \
  --arg requested_at "$(tr -d '\r\n' < "$out/requested-at.txt")" \
  '{request: $request[0], requested_at: $requested_at, usage,
    video_count: ($selection.videos | length), skipped_items: $selection.skipped,
    duplicates_removed: $selection.duplicates, result_file: "result.json"}' \
  "$out/result.json" > "$out/record.json"
printf 'Saved %s videos to %s/videos.json and video-ids.txt\n' "$(jq length "$out/videos.json")" "$out"
```

#### यूट्यूब खोज से भागो/

```bash
bash search.sh search-001
```



<a id="recover"></a>

## यदि खोज को ध्यान देने की जरूरत है

| क्या हुआ | क्या करें |
| --- | --- |
| पांच से अधिक वीडियो, या कोई नहीं | यह एक सफल खोज हो सकता है। क्वेरी को परिष्कृत करें या एक प्रतिबंधात्मक फ़िल्टर को हटा दें। totalResults इस प्रतिक्रिया का वर्णन करता है, न कि मेलिंग की कुल संख्या YouTube वीडियो। |
| 401 / 403 / 402 | क्रमश: कुंजी, youtube_search अनुमति और शेष की जाँच करें। नए प्रयास करने से पहले कारण को ठीक करें। |
| 429 | HTTP 429 पर Retry-After के अनुसार प्रतीक्षा करें। टूलकिट केवल स्पष्ट 429 प्रतिक्रियाओं को डिफ़ॉल्ट रूप से अधिकतम दो बार दोहराता है और 60 सेकंड से अधिक प्रतीक्षा होने पर रुकता है। सीधे SDK और REST उदाहरण अपने आप दोबारा प्रयास नहीं करते। |
| टाइमआउट, 5xx या एक अधूरा फ़ोल्डर | सहेजी फ़ाइलें रखें और फिर भेजने से पहले कंसोल इतिहास देखें। टूलकिट अज्ञात परिणाम वाले अनुरोध को अपने आप दोबारा नहीं भेजेगा। |

- [अनुरोध इतिहास](https://flashdata.dev/app/jobs)
- [त्रुटियाँ और स्टेटस कोड](https://flashdata.dev/hi/docs/errors/reference.md)
- [YouTube Search API Python टूलकिट](https://github.com/flashdatadev/youtube-search-api/blob/main/docs/troubleshooting.md)
