# YouTube Data 모범 사례

관련 동영상 찾기, 선택 캡션 트랙 및 프로세스 새로운 채널 업로드 반복 작업 없이.

Canonical 참고: https://flashdata.dev/ko/docs/guides/youtube-data-guide
검토: 2026-11-04 FlashData

<a id="choose"></a>

## 당신이 이미 가지고있는 정보로 시작

각 소스는 다른 질문에 답합니다. 알려진 비디오 ID 또는 채널 핸들에 대한 발견을 건너 뛰고, 작업의 필요만 비디오를 풍부하게합니다.

| 당신의 작업 | (주) | 팟캐스트 |
| --- | --- | --- |
| 관련 동영상 찾기 | youtube_search | 5명의 후보자로 시작하면, relevance에 의해 선정됩니다. |
| 알려진 비디오 검사 | youtube_metadata | 제목, 채널, 기간 및 캡션 언어 받기. |
| Summarize 또는 무슨 말을 인용 | youtube_transcript / youtube_captions | 언어 및 자동 또는 수동 트랙을 선택하십시오. |
| 최근 채널 확인 uploads | youtube_channel | 처리 된 IDs와 함께 IDs를 반환 비교하십시오. |

- [동영상 보기](https://flashdata.dev/ko/docs/guides/youtube-data-guide/reference.md#discover)
- [알려진 비디오 작업](https://flashdata.dev/ko/docs/guides/youtube-data-guide/reference.md#metadata)
- [채널을 모니터링](https://flashdata.dev/ko/docs/guides/youtube-data-guide/reference.md#channel)

<a id="setup"></a>

## 요청 예제를 실행

표시된 파일 이름을 사용하여 각 JSON 바디를 저장하십시오. Python는 아래 query.py 헬퍼를 사용합니다; cURL는 동일한 파일을 제출할 수 있습니다. 필요한 소스 권한과 사용 가능한 신용을 가진 열쇠를 사용하십시오. 각 제출은 반환된 동영상의 수에 관계없이 한 쿼리입니다.

### Python

Python 3.10+. 요청을 한 번 설치하면 아래 query.py를 저장 한 다음 각 요청에 따라 명령을 사용하십시오. 기존 출력은 재사용됩니다. 변경된 입력은 새로운 출력 파일명이 필요합니다.

#### 설치

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


### cURL

Bash. REQUEST.json 및 RESULT.json를 선택한 예에 대한 파일명과 교체하십시오. 요청을 반복하기 전에 결과를 확인합니다. 이 명령은 오류를 위해 HTTP 몸도 저장합니다.

#### 저장 된 JSON 요청 제출

```bash
(
set -eu
: "${FLASHDATA_API_KEY:?Set FLASHDATA_API_KEY first}"
test ! -e RESULT.json || { echo 'Read RESULT.json first'; exit 1; }
curl --fail-with-body --silent --show-error --max-time 70 \
  --request POST 'https://data.flashdata.dev/v1/queries/realtime' \
  --header "X-API-Key: $FLASHDATA_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @REQUEST.json --output RESULT.json
)
```



<a id="authenticate"></a>

### API 키 설정

터미널 또는 비밀 상점에서 FLASHDATA_API_KEY를 재사용하십시오. 그렇지 않으면 아래 1 개의 숨겨진 프롬프트를 사용하여 키를 입력합니다. 이 예제를 실행하는 과정에서 유지하십시오.

#### Bash

##### 키 설정

```bash
# Bash: paste the key into a hidden prompt, not into this command.
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
export FLASHDATA_API_KEY
```


#### PowerShell 7

##### 키 설정

```powershell
# PowerShell 7: paste the key into a hidden prompt.
$flashdataSecureKey = Read-Host "FlashData API key" -AsSecureString
$env:FLASHDATA_API_KEY = [System.Net.NetworkCredential]::new("", $flashdataSecureKey).Password
Remove-Variable flashdataSecureKey
```


- [API 키](https://flashdata.dev/app/api-keys)
- [에이전트 체험 및 계정 연결](https://flashdata.dev/ko/docs/guides/agent-onboarding/reference.md)

<a id="runner"></a>

### query.py를 Python 예로 저장하십시오

새로운 작업 폴더에서 query.py를 생성하고 아래의 전체 코드를 복사합니다. 이 폴더에 JSON 파일 및 기타 Python 스크립트를 저장하고, 거기에서 모든 명령을 실행하십시오.

#### query.py

```python
# query.py — submit a saved request once, then reuse its response.
import json
import os
import sys
from pathlib import Path
import requests

if len(sys.argv) != 3:
    raise SystemExit("Usage: python query.py REQUEST.json RESULT.json")
payload = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8-sig"))
output = Path(sys.argv[2])
marker = output.with_name(output.name + ".request.json")
receipt = output.with_name(output.name + ".http.json")
if marker.exists():
    if json.loads(marker.read_text()) != payload:
        raise SystemExit("Changed request: choose a new output filename.")
    if not output.exists() or not receipt.exists():
        raise SystemExit("Outcome unknown: check History before resubmitting.")
    saved = json.loads(receipt.read_text())
    if saved["status"] != 200 or json.loads(output.read_text(encoding="utf-8")).get("status") != "done":
        raise SystemExit(f"Saved request failed or incomplete; Retry-After: {saved['retry_after']}. Inspect {output}.")
    print(f"Read the saved {output}; no new query submitted.")
    raise SystemExit(0)
if output.exists():
    raise SystemExit("Output already exists. Read it or choose a new filename.")
key = os.environ["FLASHDATA_API_KEY"]
with marker.open("x", encoding="utf-8") as file:
    json.dump(payload, file)
response = requests.post("https://data.flashdata.dev/v1/queries/realtime",
                         headers={"X-API-Key": key}, json=payload,
                         timeout=70, allow_redirects=False)
output.write_text(response.text, encoding="utf-8")
receipt.write_text(json.dumps({"status": response.status_code,
                               "retry_after": response.headers.get("Retry-After")}), encoding="utf-8")
if response.status_code != 200:
    raise SystemExit(f"HTTP {response.status_code}; Retry-After: {response.headers.get('Retry-After')}")
if response.json().get("status") != "done":
    raise SystemExit(f"Inspect {output} and History before retrying.")
print(json.dumps({"saved": str(output), "usage": response.json().get("usage")}, indent=2))
```


<a id="discover"></a>

## 자주 묻는 질문

비디오 필터는 다른 결과 유형을 제외합니다; 자막은 캡션과 함께 동영상에 대한 발견을 좁힙니다. 캡션 언어를 선택하거나 필요한 트랙을 보장하지 않습니다. discover-request.json로 저장하십시오.

### discover-request.json

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

### query.py로 한 번 제출

```bash
python query.py discover-request.json search.json
```


<a id="candidates"></a>

### relevance에 의해 선택, 첫 번째 ID

query.py 및 search.json 옆에 candidates.py를 저장하고 그 폴더에서 실행하십시오. 그것은 검색 순서를 유지하고 중복된 비디오 IDs를 제거합니다. 제목, 채널 및 기간을 검사하고 다음 ID를 다음 요청에 복사합니다. 빈 목록은 후보자없이 완료 된 검색입니다.

#### candidates.py

```python
# candidates.py — read a saved response; no API calls.
import json
import re
from pathlib import Path

data = json.loads(Path("search.json").read_text(encoding="utf-8"))
if data.get("status") != "done":
    raise SystemExit("Search did not complete; inspect search.json.")
candidates, seen = [], set()
for item in (data.get("results") or [{}])[0].get("results", []):
    video_id = item.get("videoId", "")
    if not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id) or video_id in seen:
        continue
    seen.add(video_id)
    candidates.append({"videoId": video_id, "title": item.get("title"),
                       "channel": item.get("channel"), "duration": item.get("duration"),
                       "url": "https://www.youtube.com/watch?v=" + video_id})
Path("candidates.json").write_text(json.dumps(candidates, indent=2), encoding="utf-8")
print(json.dumps(candidates, indent=2))
```

#### 저장된 검색을 읽으십시오

```bash
python candidates.py
```


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

### 단축 리스트가 부족할 때만 확장

표준 검색은 max_results를 최대 20를 지원합니다. 더 넓은 수집을 위해, youtube_search_extended로 전환하고, 700로 지원하며 별도의 가격을 가지고 있습니다. 이 예제는 50에 대한 요청; 당신의 첫 번째 결과가 모든 것을 풍부하기 전에 유용 여부를 확인하십시오.

#### extended-request.json

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

#### 한 번 실행

```bash
python query.py extended-request.json extended.json
```

- [더 긴 검색을 비동기적으로 제출](https://flashdata.dev/ko/docs/reference/realtime-and-async/reference.md#async)
- [엔리치 IDs 선택](https://flashdata.dev/ko/docs/guides/enrich-youtube-videos/reference.md)

<a id="metadata"></a>

## metadata만 검색하면 기능의 필요

선택한 ID로 샘플 video_id를 대체합니다. 간단한 비디오 카드 또는 캡션 언어 체크에 대한 형식과 장을 유지하십시오. 밖으로 선을 위한 include_chapters, 또는 매체 체재를 선택할 때 include_formats를 가능하게 하십시오.

### metadata-request.json

```json
{
  "source": "youtube_metadata",
  "video_id": "FUfGcZ092b0",
  "params": {
    "include_formats": false,
    "include_chapters": false
  }
}
```

### query.py로 한 번 제출

```bash
python query.py metadata-request.json metadata.json
```

- [Metadata 응답 필드](https://flashdata.dev/ko/docs/sources/youtube_metadata/reference.md#response)
- [Media Delivery 워크플로우](https://flashdata.dev/ko/docs/guides/media-delivery-pipeline/reference.md)

<a id="tracks"></a>

### 사용 가능한 언어 검사

결과를 읽으십시오[0].transcriptLanguages를 선택하기 전에 captions. 형식, 장 및 언어는 반환된 비디오 객체에 필드입니다; 사용 기록은 외부 응답에 속합니다.

| 을 읽다 | 사용하기 |
| --- | --- |
| language | transcriptLanguages의 코드, EN 또는 zh-Hans와 같은. 이 목록은 수동과 자동적인 궤도를 구별하지 않습니다. |
| auto: true | 기존의 자동 생성된 트랙. |
| auto: false | 기존 수동으로 제공된 트랙. 두 개의 트랙 유형 사이의 미백이 없습니다. |

#### 읽기 metadata.json · 쿼리 없음

```bash
python -m json.tool metadata.json
```


<a id="captions"></a>

## 언어 선택 및 명시적으로 추적

동일한 video_id를 메타 데이터 요청으로 사용하며 언어와 자동을 변경하여 선택한 트랙과 일치합니다. youtube_transcript는 auto: true로 기본값입니다. youtube_captions는 auto: false로 기본값입니다. 기존의 캡션을 검색하고, 연설-to-text가 아닙니다.

### captions-request.json

```json
{
  "source": "youtube_transcript",
  "video_id": "FUfGcZ092b0",
  "params": {
    "language": "en",
    "auto": true
  }
}
```

### query.py로 한 번 제출

```bash
python query.py captions-request.json captions.json
```

- [Caption 모수](https://flashdata.dev/ko/docs/sources/youtube_transcript/reference.md#parameters)
- [완전한 요약](https://flashdata.dev/ko/docs/guides/youtube-summary/reference.md)

<a id="citations"></a>

### 증거로 타임스탬프를 유지

captions.json 옆에 cite-segments.py를 저장하고 그 폴더에서 실행하십시오. 결과[0].segments for citations: 시작과 끝은 초입니다. 텍스트가있는 languageCode 및 isAutoGenerated를 보존하십시오. fullText는 독서에 유용하지만 세그먼트 타이밍을 대체하지 않습니다. 선택된 트랙이 누락되면 다른 쿼리가 누락인지 결정하기 전에 격차를 기록합니다.

#### cite-segments.py

```python
import json
from pathlib import Path

response = json.loads(Path("captions.json").read_text(encoding="utf-8"))
if response.get("status") != "done":
    raise SystemExit("Inspect captions.json before continuing.")
track = (response.get("results") or [{}])[0]
if not track.get("segments"):
    raise SystemExit("No caption evidence was returned.")
for segment in track["segments"][:3]:
    url = f"https://www.youtube.com/watch?v={track['videoId']}&t={int(segment['start'])}s"
    print(segment["text"], url)
```

#### 저장된 캡션을 읽으십시오 · API 통화 없음

```bash
python cite-segments.py
```


<a id="channel"></a>

## 알려진 채널에서 새로운 동영상만 처리

채널 핸들을 사용 하 고 경계 video_limit (1–100). 결과[0].videos는 반환 최근 목록입니다; videoCount는 채널 메타 데이터, 반환된 항목의 수입니다. 당신이 관찰 할 필요가 업로드를 커버하는 제한 및 일정을 선택하십시오.

### channel-request.json

```json
{
  "source": "youtube_channel",
  "handle": "@TED",
  "params": {
    "video_limit": 10
  }
}
```

### query.py로 한 번 제출

```bash
python query.py channel-request.json channel.json
```


<a id="channel-diff"></a>

### 큐와 완료 체크 포인트 유지

query.py 및 channel.json 옆에 channel-queue.py를 저장하고 그 폴더에서 실행하십시오. new-ids.json를 생성하지 않고 실행하고 IDs에 대한 증거를 저장합니다. --commit를 실행하면 모든 누락 된 ID가 성공합니다. 실패는 체크 포인트를 변경하지 않습니다. 이 예제를 위해 채널당 하나의 디렉토리와 하나의 worker를 사용합니다.

#### channel-queue.py

```python
# channel-queue.py — plan first; commit only after every queued video is processed.
import json
import re
import sys
from pathlib import Path

checkpoint = Path("processed-ids.json")
processed = set(json.loads(checkpoint.read_text()) if checkpoint.exists() else [])
queue = Path("new-ids.json")
if sys.argv[1:] == ["--commit"]:
    processed.update(json.loads(queue.read_text()))
    temporary = checkpoint.with_suffix(".tmp")
    temporary.write_text(json.dumps(sorted(processed)), encoding="utf-8")
    temporary.replace(checkpoint)
    queue.unlink()
    print("Checkpoint saved.")
elif sys.argv[1:]:
    raise SystemExit("Usage: python channel-queue.py [--commit]")
else:
    data = json.loads(Path("channel.json").read_text(encoding="utf-8"))
    if data.get("status") != "done":
        raise SystemExit("Channel query did not complete.")
    ids = dict.fromkeys(video.get("videoId", "") for video in
                        (data.get("results") or [{}])[0].get("videos", []))
    new = [value for value in ids if re.fullmatch(r"[A-Za-z0-9_-]{11}", value)
           and value not in processed]
    if queue.exists() and json.loads(queue.read_text()) != new:
        raise SystemExit("Finish the existing queue before replacing it.")
    queue.write_text(json.dumps(new, indent=2), encoding="utf-8")
    print(json.dumps(new, indent=2))
```

#### 계획 → 프로세스 → 커밋

```bash
python channel-queue.py
# Process every ID in new-ids.json and save its result first.
python channel-queue.py --commit
```

- [일정 및 재사용 자격](https://flashdata.dev/ko/docs/guides/recurring-tasks/reference.md)
- [Enrich a list 의 동영상](https://flashdata.dev/ko/docs/guides/enrich-youtube-videos/reference.md)

<a id="channel-checkpoint"></a>

### 신선한 채널 체크 deliberately 시작

Query helper는 저장된 응답을 재사용합니다. 다음 예정된 체크의 경우, 새로운 결과 파일 이름을 사용하여, 검사, 다음 쿼리 단계에 대한 channel.json에 대한 완료된 응답을 복사합니다. 실행 중 processed-ids.json 유지. 이 최근 목록은 전체 채널 수출 또는 이벤트 스트림이 아닙니다.

#### 다음 체크 · 신선한 파일명 선택

```bash
python query.py channel-request.json channel-next.json
```

#### 확인 상태가 완료된 후

```bash
python -c "from shutil import copyfile; copyfile('channel-next.json', 'channel.json')"
```


<a id="suggestions"></a>

## 쿼리를 개선하기 위해 제안을 사용

제안은 결과에 반환 구문[0], 비디오 레코드가 아닙니다. 유용한 구문을 선택하고 별도의 youtube_search 요청을 만듭니다. 언어와 지역은 청중들을 위해 연구하고 있습니다.

### suggestions-request.json

```json
{
  "source": "youtube_suggestions",
  "query": "battery recycling",
  "params": {
    "language": "en",
    "region": "US"
  }
}
```

### query.py로 한 번 제출

```bash
python query.py suggestions-request.json suggestions.json
```


<a id="license"></a>

## 사용 허가 없이 사용 허가 라벨을 저장

youtube_trainability는 비디오를 위한 라이센스 라벨을 반환합니다. 허용: ["all"]는 Creative Commons에 맵; ["none"]는 또한 라이센스 메타 데이터를 덮습니다. 비디오 ID, 소스 응답 및 검색 날짜 유지. 이 라벨은 다운로드, 재사용 또는 훈련 권한을 부여하지 않습니다.

### license-request.json

```json
{
  "source": "youtube_trainability",
  "video_id": "FUfGcZ092b0"
}
```

### query.py로 한 번 제출

```bash
python query.py license-request.json license.json
```


<a id="operations"></a>

## 앱 및 에이전트에 대한 작업을 경계

| ᄋᄋᄋ | - 연혁 |
| --- | --- |
| 자주 묻는 질문 | 주제 작업 : 한 검색, 한 선택된 비디오의 메타 데이터 및 한 선택된 캡션 트랙. 앱에서 통화 예산을 강화하고, 각 소스를 별도로 가격합니다. |
| 실제 입력에 의한 재사용 | Metadata: 비디오 ID + 옵션. Captions: 비디오 ID + 언어 + 트랙. 채널 스냅 샷은 또한 retrieval 시간을 필요로하거나 ID를 실행합니다. |
| 누락된 증거에 중지 | 빈 발견 결과 또는 침묵 스위치 캡션 트랙을 재개하지 마십시오. 사용자 또는 워크플로우가 다음 작업을 선택할 수 있도록 갭을 반환합니다. |
| 보존 및 실패 | 성공적인 응답을 가진 사용법을 저장하십시오. 429에, 명예 Retry-After; 불확실한 제출 후에, 다른 지불한 조회의 앞에 History를 검사하십시오. |

- [Realtime 및 동기화](https://flashdata.dev/ko/docs/reference/realtime-and-async/reference.md)
- [Batch와 대량](https://flashdata.dev/ko/docs/reference/batch-and-bulk/reference.md)
- [오류 및 재난](https://flashdata.dev/ko/docs/errors/reference.md#retries)
- [현재 가격 및 균형](https://flashdata.dev/ko/docs/guides/credits-and-billing/reference.md)
