# 한 비디오의 메타 데이터를 검색

YouTube 비디오 ID를 제목, 채널, 기간 및 사용 가능한 수의 저장된 레코드로 설정하십시오. 원래 응답을 유지하고 그것을 따라 사용.

Canonical 참고: https://flashdata.dev/ko/docs/guides/video-metadata-recipe
검토: 2026-11-05 FlashData

<a id="prepare"></a>

## 시작하기 전에

youtube_metadata 권한 및 사용 가능한 크레딧으로 키를 사용합니다. 제품 정보 Python 3.10+ 요청, 또는 Bash 으로 cURL 7.76+ 및 jq. Windows에서 Git Bash를 Bash 버전으로 사용하십시오.

- [API 키 받기](https://flashdata.dev/app/api-keys)
- [에이전트 체험 및 계정 연결](https://flashdata.dev/ko/docs/guides/agent-onboarding/reference.md)
- [크레딧 및 가격](https://flashdata.dev/ko/docs/guides/credits-and-billing/reference.md)

<a id="input"></a>

## 1. 1개의 영상을 선택하십시오

비디오 메타 데이터 폴더를 만들고 request.json를 저장하십시오. 그 폴더에 터미널을 엽니다. video_id를 11-character ID를 시계 URL 또는 YouTube Search 결과로 대체하십시오; 가득 차있는 URL를 통과하지 마십시오.

두 가지 옵션 플래그를 명시적으로 설정: 이 첫 번째 요청 omits 미디어 형식과 챕터. 비디오 또는 캡션을 다운로드하지 않고 메타 데이터를 검색합니다.

### video-metadata/request.json

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


<a id="run"></a>

## 2. Fetch를 저장하고 metadata

하나의 버전을 선택하고 request.json 옆에 스크립트를 저장하십시오. 그것은 FLASHDATA_API_KEY를 읽거나 숨겨지은 프롬프트에서 당신의 열쇠를 요구한다. 에이전트는 자신의 비밀 저장소에서 환경 변수를로드해야합니다.

snapshot-001를 출력 폴더로 실행합니다. 새로운 폴더는 1개의 메타데이터 쿼리를 보내고 보고된 사용법을 저장합니다. 스크립트는 video.json를 작성하기 전에 요청된 ID와 정확히 하나의 비디오를 포함하는 성공적인 응답을 확인합니다.

### Python

#### Python 환경에서 설치

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

#### video-metadata/metadata.py

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

#### video-metadata/에서 실행

```bash
python metadata.py snapshot-001
```


### Bash

#### 당신의 도구를 확인

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

#### video-metadata/metadata.sh

```bash
#!/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"
```

#### video-metadata/에서 실행

```bash
bash metadata.sh snapshot-001
```



<a id="output"></a>

## 3. 비디오 녹화 읽기

snapshot-001/video.json.에 저장된 <video ID>를 성공적으로 인쇄하십시오 정확한 제출된 요청, requested_at 및 사용을위한 전체 메타 데이터 개체 및 record.json에 대한 파일이 읽기. 이 파일을 읽는 것은 API 통화가 없습니다.

### Python

#### 현지 정보

```bash
python -m json.tool snapshot-001/video.json
python -m json.tool snapshot-001/record.json
```


### Bash

#### 현지 정보

```bash
cat snapshot-001/video.json
cat snapshot-001/record.json
```



<a id="expected"></a>

### 예 출력

설명 video.json. 반환된 값은 다를 수 있습니다. 스크립트는 null 값을 포함한 모든 사용 가능한 필드를 보존하고 result.json의 전체 응답을 유지합니다.

#### video-metadata/snapshot-001/video.json

```json
{
  "videoId": "FUfGcZ092b0",
  "title": "Example research video",
  "channel": "Example channel",
  "duration": 120,
  "viewCount": null,
  "transcriptLanguages": [
    "en"
  ]
}
```


<a id="fields"></a>

### 관련 기사

| - 연혁 | 사용하기 |
| --- | --- |
| videoId | 기록의 안정되어 있는 열쇠. 제목 및 채널 표시 이름은 변경할 수 있습니다. |
| duration | 몇 초에 비디오 길이. 알 수없는 null 값을 보존합니다. |
| viewCount / likeCount / commentCount | 이 스냅샷에서 사용할 수 있습니다. Null 또는 누락은 알 수 없습니다. 0은보고 된 수입니다. |
| transcriptLanguages | 별도의 캡션 요청을 위한 Candidate 언어 코드. 이 목록은 트랙이 자동 또는 수동인지 식별하지 않습니다. |


<a id="reuse"></a>

## 스냅 샷을 재사용하거나 다른 요청

저장 응답에서 video.json 및 record.json를 재구축하는 동일한 명령을 실행하십시오. 열쇠 또는 네트워크 요구는 필요하지 않습니다. 상단 레벨 request.json 편집은 스냅샷-001로 저장된 입력을 변경하지 않습니다.

### Python

#### Reuse 저장된 자료

```bash
python metadata.py snapshot-001
```


### Bash

#### Reuse 저장된 자료

```bash
bash metadata.sh snapshot-001
```


- [저장 및 재사용 결과](https://flashdata.dev/ko/docs/guides/save-results/reference.md)

<a id="chapters"></a>

### 사용 가능한 장을 포함

장 마커를 포함 하 여,이 버전과 request.json를 교체 하 고 새로운 출력 폴더를 사용 하 여. include_chapters: true 사용할 수 있을 때 장 반환; 그것은 그들을 만들지 않습니다. include_chapters와 include_formats가 기본적으로 true에 omitted 경우.

#### video-metadata/request.json

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

#### Python

##### 다른 스냅샷을 요청

```bash
python metadata.py snapshot-002
```


#### Bash

##### 다른 스냅샷을 요청

```bash
bash metadata.sh snapshot-002
```


- [Metadata 필드 및 옵션](https://flashdata.dev/ko/docs/sources/youtube_metadata/reference.md)

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

## metadata가 사용할 수 없는 경우

| 어떤 일이 있었는지 | 해결 방법 |
| --- | --- |
| 유효성 video_id | 11-character ID만 사용하십시오. 입력 검증은 요청을 보내기 전에 중지합니다. |
| 개인, 제거 또는 제한 된 비디오 | ID에 대한 실패를 유지하십시오. 소스 오류를 확인하고 반복적으로 동일한 항목을 제출하는 접근 가능한 비디오를 선택하십시오. |
| 빈 결과 또는 다른 videoId | 스크립트는 video.json를 작성하지 않고 중지합니다. 기록을 사용하기 전에 저장된 요청 및 응답을 검사합니다. |
| 계산, 장 또는 언어 | 일치하는 metadata 기록은 아직도 성공될 수 있습니다. unavailable 필드를 알 수없는 보존; 발명 된 값으로 채우지 마십시오. |
| 401 / 403 / 402 | 키, youtube_metadata 권한 및 균형 확인, 각각, 새로운 시도 전에. |
| 429 | response-headers.txt에서 Retry-After를 읽고 기다립니다. 스크립트는 자동으로 retries하지 않습니다. |
| Timeout, 5xx, 잘못된 JSON 또는 불완전 폴더 | 다시 제출하기 전에 History를 시도하고 확인하십시오. 폴더를 재사용하면 새로운 요청이 없습니다. |

### Python

metadata.py 옆에 inspect_metadata.py를 저장하고, 그 후에 그것을 달립니다.

#### video-metadata/inspect_metadata.py

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

#### 로컬로 검사

```bash
python inspect_metadata.py
```


### Bash

#### 로컬로 검사

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


- [회사연혁](https://flashdata.dev/app/jobs)
- [오류와 상태 코드](https://flashdata.dev/ko/docs/errors/reference.md)

<a id="next"></a>

## 작업 흐름에 비디오 사용

videoId를 사용하여 검색 결과 또는 dataset에 이 레코드에 가입하십시오. 말한 내용의 경우, 다음의 특정 캡션 트랙을 검색합니다. 몇몇 IDs를 위해, enrichment 가이드를 사용하십시오. 이들은 자신의 허가와 책임과 분리된 요청입니다.

- [타임스탬프 캡션 검색](https://flashdata.dev/ko/docs/guides/timestamped-captions-recipe/reference.md)
- [Enrich 선택한 비디오 IDs](https://flashdata.dev/ko/docs/guides/enrich-youtube-videos/reference.md)
