본문으로 건너뛰기
KO
API 키 받기
문서 둘러보기

API 참조

Bulk 처리 API

생성 및 제어 파일 기반 YouTube 작업, 그 결과가 나타납니다.

이 페이지의 내용

API 플레이그라운드

소스를 선택하고 완전한 Python 또는 Bash 워크플로우, 단일 요청 또는 샘플 응답을 복사하십시오. 놀이터 미리보기 코드; 그것은 일을 제출하지 않습니다. 모든 결과의 업로드, 상태 확인 및 검색을 완료합니다.

소스 매개 변수

Bulk 워크플로우 구축

로컬 UTF-8 파일, 하나의 YouTube ID 라인, 최대 2 GiB. 입력 요구 사항.

결과 납품

FlashData API를 통해 결과를 검색할 수 있습니다.

Bulk 완료 webhookManifest-completion 알림 및 검증
POSThttps://api.flashdata.dev/v2/bulk-jobs
Python 3 · standard library
import gzip
import json
import os
from pathlib import Path
import random
import re
import shutil
import time
import urllib.error
import urllib.parse
import urllib.request

api_key = "YOUR_API_KEY"
api_url = "https://api.flashdata.dev/v2"
input_file = Path("video-ids.txt")
output_dir = Path("bulk-results")
bulk_id = ""  # Paste a saved Bulk ID to monitor/retrieve it without submitting again.
poll_timeout_seconds = 1800
payload = {
    "source": "youtube_trainability",
    "options": {},
}

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

opener = urllib.request.build_opener(NoRedirect())
os.umask(0o077)

def api(path, method="GET", body=None):
    data = None if body is None else json.dumps(body).encode("utf-8")
    headers = {"X-API-Key": api_key, "Content-Type": "application/json"}
    for attempt in range(5):
        try:
            request = urllib.request.Request(api_url + path, data=data, headers=headers, method=method)
            with opener.open(request, timeout=60) as response:
                return json.load(response)
        except urllib.error.HTTPError as error:
            if method != "GET" or error.code not in (429, 502, 503, 504) or attempt == 4:
                raise
            retry_after = error.headers.get("Retry-After", "")
            delay = min(120, int(retry_after)) if retry_after.isdigit() else 2 ** attempt
            time.sleep(delay + random.random())

def result_location(path):
    request = urllib.request.Request(api_url + path, headers={"X-API-Key": api_key})
    try:
        with opener.open(request, timeout=60):
            raise RuntimeError("Expected a 302 result redirect")
    except urllib.error.HTTPError as error:
        if error.code != 302:
            raise
        location = error.headers.get("Location", "")
    parsed = urllib.parse.urlsplit(location)
    if parsed.scheme != urllib.parse.urlsplit(api_url).scheme or not parsed.hostname or parsed.username or parsed.password:
        raise RuntimeError("Invalid signed storage URL")
    return location

if not bulk_id:
    if not input_file.is_file() or not 1 <= input_file.stat().st_size <= 2147483648:
        raise ValueError("Use a nonempty UTF-8 ID file up to 2 GiB")
    created = api("/bulk-jobs", "POST", payload)
    bulk_id = created["job"]["id"]
    if not re.fullmatch(r"bulk_[A-Za-z0-9_-]{8,}", bulk_id):
        raise RuntimeError("Invalid Bulk ID")
    work = output_dir / bulk_id
    work.mkdir(parents=True, exist_ok=True)
    (work / "created.json").write_text(json.dumps(created, indent=2))
    print("Saved Bulk ID:", bulk_id, flush=True)
    upload = created["upload"]
    upload_url = urllib.parse.urlsplit(upload["href"])
    if upload["method"] != "PUT" or upload_url.scheme != urllib.parse.urlsplit(api_url).scheme or not upload_url.hostname or upload_url.username or upload_url.password:
        raise RuntimeError("Invalid signed upload URL")
    with input_file.open("rb") as file:
        request = urllib.request.Request(upload["href"], data=file, method="PUT", headers={
            "Content-Type": upload["contentType"], "Content-Length": str(input_file.stat().st_size)
        })
        with opener.open(request, timeout=120) as response:
            response.read()
    api("/bulk-jobs/" + bulk_id + "/start", "POST")

if not re.fullmatch(r"bulk_[A-Za-z0-9_-]{8,}", bulk_id):
    raise ValueError("Invalid Bulk ID")
work = output_dir / bulk_id
work.mkdir(parents=True, exist_ok=True)
deadline = time.monotonic() + poll_timeout_seconds
while True:
    job = api("/bulk-jobs/" + bulk_id)["job"]
    (work / "status.json").write_text(json.dumps(job, indent=2))
    print(job["status"], job["input"], job["counts"], flush=True)
    if job["status"] == "completed":
        break
    if job["status"] in ("paused", "failed", "cancelled", "awaiting_upload"):
        raise RuntimeError(json.dumps({"id": bulk_id, "status": job["status"], "pauseReason": job.get("pauseReason"), "error": job.get("error")}))
    if time.monotonic() >= deadline:
        raise TimeoutError("Job still running. Set bulk_id to " + bulk_id + " and rerun to continue monitoring.")
    time.sleep(10 + random.random())

manifest_url = result_location("/bulk-jobs/" + bulk_id + "/results")
with opener.open(manifest_url, timeout=60) as response:  # No API key sent to storage.
    manifest = json.load(response)
(work / "manifest.json").write_text(json.dumps(manifest, indent=2))
for part in manifest["parts"]:
    number = part["number"]
    if type(number) is not int or number < 1:
        raise RuntimeError("Invalid part number")
    path = "/bulk-jobs/" + bulk_id + "/results/" + str(number)
    if part["href"] != api_url + path:
        raise RuntimeError("Unexpected part API URL")
    storage_url = result_location(path)
    compressed = work / ("part-" + str(number) + ".jsonl.gz")
    with opener.open(storage_url, timeout=120) as response, compressed.open("wb") as file:
        shutil.copyfileobj(response, file, 1024 * 1024)
    with compressed.open("rb") as file:
        gzipped = file.read(2) == b"\x1f\x8b"
    reader = gzip.open(compressed, "rb") if gzipped else compressed.open("rb")
    with reader, (work / ("part-" + str(number) + ".jsonl")).open("wb") as file:
        shutil.copyfileobj(reader, file, 1024 * 1024)
print("Saved manifest and decoded NDJSON parts in", work)
생성, 업로드, 시작, 모니터 및 모든 부품을 검색X-API-Key 인증

종료점

모든 엔드포인트 사용 https://api.flashdata.dev/v2. 작업 → 비디오-ID 파일을 업로드 → 시작 → 모니터 → 표시 및 모든 결과 부분을 검색합니다.

의 특징의논하기조치
POST/v2/bulk-jobsBulk 작업 만들기
POST/v2/bulk-jobs/{bulkId}/start업로드 및 시작
GET/v2/bulk-jobs/{bulkId}업무 상태
GET/v2/bulk-jobs회사연혁
POST/v2/bulk-jobs/{bulkId}/pause작업 일시
PATCH/v2/bulk-jobs/{bulkId}작업 옵션 업데이트
POST/v2/bulk-jobs/{bulkId}/resume직업을 구합니다
DELETE/v2/bulk-jobs/{bulkId}업무 종료
GET/v2/bulk-jobs/{bulkId}/results결과 표시
GET/v2/bulk-jobs/{bulkId}/results/{partNumber}관련 제품

인증 및 입력

FLASHDATA_API_KEY를 선택한 소스에 액세스하는 키로 설정합니다. 창조, 통제 및 결과를 위한 동일한 열쇠 그리고 계정을 재사용하십시오. 처리는 계정의 잔고 및 정상적인 per-source 가격을 사용합니다. YouTube Download는 소유자 접근 및 options.storage를 요구합니다.

Bulk-api/라는 작업 폴더를 만들고 이 예제를 실행합니다. 놀이터의 전체 Python 워크플로우는 Python 3.10+ 표준 라이브러리를 사용합니다. 개별 Python 엔드포인트 예제는 아래 요청이 필요합니다. cURL 예제는 Bash, cURL 7.76+, jq 및 gzip을 사용합니다. 각 행동에 대한 하나의 언어를 선택하여 중복 작업을 만들거나 시작할 수 없습니다.

입력은 1개의 11-character YouTube ID를 가진 UTF-8 파일, 2 GiB까지 입니다. 제품 정보 IDs, 아니 URLs. 업로드하기 전에 중복 IDs 제거; 반복 IDs는 별도로 처리됩니다.

(주)공유 옵션
youtube_metadatainclude_formats, include_chapters
youtube_transcript언어, 자동차
youtube_captions언어, 자동차
youtube_trainability옵션 없음
youtube_download미디어 옵션 및 저장 대상
Python 신뢰성
python -m pip install requests

요청 필드 생성

- 연혁유형제품 정보
sourcestring관련 기사 모든 입력 ID에 대한 지원되는 소스.
optionsobject공유 소스 옵션 데이터 소스는 result_storage를 설정할 수 있습니다; YouTube Download는 저장을 요구합니다.
callback_urlstring옵션 공개 HTTPS 완료 콜백. 표시된 출판 후의 문장.

Bulk 작업 만들기

작업을 생성한 뒤 한 줄에 하나의 11자 YouTube 동영상 ID가 담긴 UTF-8 텍스트 파일을 upload.href에 업로드하고 start를 호출하세요. 작업 생성만으로 처리가 시작되지는 않습니다.

이 예제는 video-ids.txt를 작성하고 201 영수증을 bulk-created.json로 저장합니다. 그 영수증 개인 및 재사용 job.id를 나중에 요청하십시오. awaiting_upload에서 일자리를 창출; 업로드 URL는 15 분 후에 만료됩니다.

끝점
POST https://api.flashdata.dev/v2/bulk-jobs
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 bulk_create.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

bulk_create.py
import json
import os
from pathlib import Path

import requests

os.umask(0o077)
Path("video-ids.txt").write_bytes(b"jNQXAC9IVRw\ndQw4w9WgXcQ\n")
response = requests.post(
    "https://api.flashdata.dev/v2/bulk-jobs",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    json={"source": "youtube_metadata", "options": {"include_formats": False}},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
receipt = response.json()
Path("bulk-created.json").write_text(json.dumps(receipt, indent=2), encoding="utf-8")
print(json.dumps(receipt["job"], indent=2))
Bulk-api/에서 실행
python bulk_create.py

응답 및 요청 schema

HTTP 상태은둔
201Bulk 작업은 15-minute 직접 업로드 URL로 만든
401인증 필요 또는 잘못된
422자주 묻는 질문
503필수 조건 또는 카탈로그는 일시적으로 사용할 수 없습니다
요청 본문
{
  "$ref": "#/components/schemas/CreateBulkJobRequest"
}
201 · application/json
{
  "$ref": "#/components/schemas/BulkJobCreated"
}

업로드 및 시작

업로드 UTF-8 비디오 ID 파일을 처리 시작, 최대 2 GiB (2147483648 바이트). 시작 후 변경된 파일을 유지하십시오.

1 년 전 PUT video-ids.txt 영수증에 upload.href 으로 upload.contentType, 없이 X-API-Key. 예 호출은 업로드 후 만 시작됩니다. 업로드된 파일을 수정한 후.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
끝점
POST https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/start
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 bulk_start.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

bulk_start.py
import json
import os
from pathlib import Path

import requests

receipt = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))
upload = receipt["upload"]
if upload["method"] != "PUT" or not upload["href"].startswith("https://"):
    raise ValueError("Expected an HTTPS PUT upload URL")
# Stream the file to storage without the FlashData key.
with open("video-ids.txt", "rb") as file:
    response = requests.put(
        upload["href"], data=file,
        headers={"Content-Type": upload["contentType"]},
        timeout=300, allow_redirects=False,
    )
    response.raise_for_status()
    if not 200 <= response.status_code < 300:
        raise RuntimeError("Upload did not complete; do not start the job yet")

bulk_id = receipt["job"]["id"]
response = requests.post(
    f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}/start",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
print(json.dumps(response.json()["job"], indent=2))
Bulk-api/에서 실행
python bulk_start.py

응답하기

HTTP 상태은둔
200Bulk 일 시작 또는 그것의 현재 idempotent 국가
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
409자원 상태 또는 idempotency 분쟁
422자주 묻는 질문
503필수 조건 또는 카탈로그는 일시적으로 사용할 수 없습니다
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

업무 상태

job.status, 입력, 카운트, pauseReason 및 오류를 읽으십시오. 지연과 동일한 ID를 다시 체크; 완료된 의미는 표시되지 않습니다, 모든 비디오가 성공.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
끝점
GET https://api.flashdata.dev/v2/bulk-jobs/{bulkId}
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 bulk_status.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

bulk_status.py
import json
import os
from pathlib import Path

import requests

bulk_id = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))["job"]["id"]
response = requests.get(
    f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
Path("bulk-job.json").write_text(json.dumps(response.json(), indent=2), encoding="utf-8")
print(json.dumps(response.json()["job"], indent=2))
Bulk-api/에서 실행
python bulk_status.py

응답하기

HTTP 상태은둔
200Bulk 작업 상태
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

회사연혁

응답은 자료와 pagination를 포함합니다. pagination.nextCursor를 다음 요청의 커서 쿼리 매개 변수로 null를 전달합니다. 1에서 50로 제한을 사용하십시오. 기본값은 20입니다.

제품 설명위치관련 상품
cursorquery선택 사항 · {"type":"string","maxLength":512}
limitquery선택 사항 · {"type":"integer","minimum":1,"maximum":50,"default":20}
끝점
GET https://api.flashdata.dev/v2/bulk-jobs
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 list_bulk_jobs.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

list_bulk_jobs.py
import json
import os
from pathlib import Path

import requests

response = requests.get(
    "https://api.flashdata.dev/v2/bulk-jobs?limit=20",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
Bulk-api/에서 실행
python list_bulk_jobs.py

응답하기

HTTP 상태은둔
200Bulk 구인 페이지
401인증 필요 또는 잘못된
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobPage"
}

작업 일시

새 제출 및 결과 포장을 일시 중지합니다. 기존 작업은 원래 설정과 비용으로 계속됩니다. 준비 할 때 작업을 재개합니다.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
끝점
POST https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/pause
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 pause_bulk_job.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

pause_bulk_job.py
import json
import os
from pathlib import Path

import requests

bulk_id = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))["job"]["id"]
response = requests.post(
    f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}/pause",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
Bulk-api/에서 실행
python pause_bulk_job.py

응답하기

HTTP 상태은둔
200Paused 대량 일 또는 그것의 현재 idempotent 국가
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

작업 옵션 업데이트

업로드를 기다리는 동안 업데이트 옵션, 또는 모든 입력 전에 일시 중지되었습니다. 기존 작업은 설정을 유지한다. 패싱이 진행중인 경우, 대기하고 409 응답을 다시 시도하십시오. 모든 입력이 읽은 후에, 납품 credentials만 개정될 수 있습니다. callback_url를 null로 설정하여 제거하십시오.

이 예제는 완료 콜백을 제거합니다. 소스 옵션을 변경하려면, 대신 옵션 객체를 보냅니다. 처음 일시 중지하고 일시 중지를 기다립니다. 409는 업데이트가 아직 적용되지 않습니다. 기존의 아이 작업은 원래의 옵션을 유지.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
끝점
PATCH https://api.flashdata.dev/v2/bulk-jobs/{bulkId}
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 update_bulk_job.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

update_bulk_job.py
import json
import os
from pathlib import Path

import requests

bulk_id = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))["job"]["id"]
response = requests.patch(
    f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    json={"callback_url": None},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
Bulk-api/에서 실행
python update_bulk_job.py

응답 및 요청 schema

HTTP 상태은둔
200업데이트 된 대량 작업 상태
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
409자원 상태 또는 idempotency 분쟁
422자주 묻는 질문
요청 본문
{
  "$ref": "#/components/schemas/UpdateBulkJobRequest"
}
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

직업을 구합니다

pauseReason를 먼저 수정하여 크레딧을 추가하거나 저장 자격 증명을 업데이트 한 다음 동일한 Bulk ID를 다시 시작합니다.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
끝점
POST https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/resume
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 resume_bulk_job.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

resume_bulk_job.py
import json
import os
from pathlib import Path

import requests

bulk_id = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))["job"]["id"]
response = requests.post(
    f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}/resume",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
Bulk-api/에서 실행
python resume_bulk_job.py

응답하기

HTTP 상태은둔
200현재 대량 일 국가
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

업무 종료

새 제출을 중지합니다. 기존 작업은 여전히 finish 및 정상적인 비용을 처리 할 수 있습니다. 취소된 작업은 최종 결과를 게시하지 않습니다.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
끝점
DELETE https://api.flashdata.dev/v2/bulk-jobs/{bulkId}
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 cancel_bulk_job.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

cancel_bulk_job.py
import json
import os
from pathlib import Path

import requests

bulk_id = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))["job"]["id"]
response = requests.delete(
    f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
print(json.dumps(response.json(), indent=2))
Bulk-api/에서 실행
python cancel_bulk_job.py

응답하기

HTTP 상태은둔
200현재 대량 일 국가
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

결과 표시

JSON를 다운로드하는 리디렉션을 따라 결과 파일을 검색하는 링크를 사용합니다. Fetch는 API 키가 없는 저장 URLs를 서명했습니다. 결과는 Bulk 작업 전체가 완료된 후 24 시간 동안 사용할 수 있습니다.

인증된 API 요청은 Location 헤더와 함께 302를 반환합니다. X-API-Key 없이 별도의 요청으로 해당 HTTPS 저장소 URL을 가져오세요. 예제는 manifest.json을 저장합니다. 409는 결과가 아직 준비되지 않았음을, 410은 결과가 만료되었음을 뜻합니다.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
끝점
GET https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/results
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 bulk_manifest.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

bulk_manifest.py
import json
import os
from pathlib import Path

import requests

bulk_id = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))["job"]["id"]
response = requests.get(
    f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}/results",
    headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
    timeout=30, allow_redirects=False,
)
response.raise_for_status()
if response.status_code != 302:
    raise RuntimeError(f"Expected a manifest redirect, got {response.status_code}")
url = response.headers["Location"]
if not url.startswith("https://"):
    raise ValueError("Expected an HTTPS storage URL")

manifest = requests.get(url, timeout=120)  # No FlashData API key.
manifest.raise_for_status()
Path("manifest.json").write_text(json.dumps(manifest.json(), indent=2), encoding="utf-8")
print(json.dumps(manifest.json(), indent=2))
Bulk-api/에서 실행
python bulk_manifest.py

응답하기

HTTP 상태은둔
200JSON는 리디렉션을 따르는 후 다운로드
302짧은 라이브 개인 R2 URL로 이동; API 자격은 전달되지 않아야 합니다. · Location
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
409자원 상태 또는 idempotency 분쟁
410유지된 결과가 만료되었습니다
200 · application/json
{
  "type": "object",
  "additionalProperties": true
}

관련 제품

manifest.json에서 각 parts[].number를 사용하십시오. 각 엔드포인트는 302를 gzip NDJSON 파일로 반환합니다. API 키, decompress없이 다운로드 한 다음 라인 당 JSON 객체를 파고 있습니다. 0기반 색인에 가입하십시오. 예를 들어 모든 부품을 검색하고 .ndjson.gz 및 .ndjson 파일을 모두 유지하십시오.

제품 설명위치관련 상품
bulkIdpath필수 · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
partNumberpath필수 · {"type":"integer","minimum":0}
끝점
GET https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/results/{partNumber}
X-API-Key: YOUR_API_KEY

bulk-created.json 옆에 대량api/에서 bulk_parts.py를 저장하십시오. 완전한 스크립트를 복사하고, 아래 명령어를 실행합니다.

bulk_parts.py
import json
import os
from pathlib import Path

import requests
import gzip
import shutil

bulk_id = json.loads(Path("bulk-created.json").read_text(encoding="utf-8"))["job"]["id"]
manifest = json.loads(Path("manifest.json").read_text(encoding="utf-8"))
for part in manifest["parts"]:
    number = part["number"]
    response = requests.get(
        f"https://api.flashdata.dev/v2/bulk-jobs/{bulk_id}/results/{number}",
        headers={"X-API-Key": os.environ["FLASHDATA_API_KEY"]},
        timeout=30, allow_redirects=False,
    )
    response.raise_for_status()
    if response.status_code != 302:
        raise RuntimeError(f"Expected a part redirect, got {response.status_code}")
    url = response.headers["Location"]
    if not url.startswith("https://"):
        raise ValueError("Expected an HTTPS storage URL")

    # Save the original gzip bytes; do not decompress twice.
    with requests.get(url, stream=True, timeout=120) as download:
        download.raise_for_status()
        with open(f"part-{number}.ndjson.gz", "wb") as file:
            download.raw.decode_content = False
            shutil.copyfileobj(download.raw, file)
    with gzip.open(f"part-{number}.ndjson.gz", "rt", encoding="utf-8") as rows:
        with open(f"part-{number}.ndjson", "w", encoding="utf-8") as file:
            for line in rows:
                file.write(line)
                print(json.dumps(json.loads(line)))
Bulk-api/에서 실행
python bulk_parts.py

응답하기

HTTP 상태은둔
200Gzip-compressed NDJSON는 리디렉션 후 다운로드
302짧은 라이브 개인 R2 URL로 이동; API 자격은 전달되지 않아야 합니다. · Location
401인증 필요 또는 잘못된
404검색 결과를 찾을 수 없음 한국어 사전에
409자원 상태 또는 idempotency 분쟁
410유지된 결과가 만료되었습니다
200 · application/x-ndjson
{
  "type": "string"
}

업무 상태 및 유지

결과는 Bulk 작업 전체가 완료된 후 24 시간 동안 사용할 수 있습니다. expiresAt의 앞에 그들을 저장하십시오. 당신의 목적지에 있는 매체는 당신의 물통의 보유 정책을 따릅니다. 완료된 작업은 실패한 영상을 포함할 수 있습니다; counts.invalid 기록은 입력 선을 거부했습니다.

(주)다음 작업
awaiting_upload파일 업로드 및 통화 시작.
running뒤로 동일한 ID를 오염; input.complete는 검사가 완료된지 보여줍니다.
pausedpauseReason를 읽으십시오, 그것을 고치고, 그 후에 재개하십시오.
finalizing결과 포장 및 표시를 기다리십시오.
completed표시 및 모든 부분을 다운로드합니다. 각 행의 상태와 오류를 검사합니다.
failed / cancelledInspect 오류 및 저장된 상태. 최종적으로 게시되지 않습니다.

저장 납품

공급자를 구성하고 정확한 요청 필드를 미리 볼 수있는 놀이터를 사용합니다. Customer storage credentials는 선택한 저장 객체에 속합니다. X-API-Key는 FlashData API 요청만 인증합니다.

(주)요청 필드를 생성제품 정보
Metadata, 성적표, captions, 라이센스 확인options.result_storage옵션. Copies NDJSON 결과 부품과 버킷에 나타났습니다.
youtube_downloadoptions.storage관련 기사 당신의 물통에 매체를 전달하십시오; result_storage와 browser_delivery는 받아들여지지 않습니다.

전달된 파일을 찾습니다

데이터는 마지막으로 작성하고 객체 키, 크기 및 SHA-256 체크섬을 나열합니다. 그것은 다릅니다. FlashData 예시, 어떤 목록 API href 값. YYYYMMDD는 UTC Bulk 생성 날짜를 사용합니다. 미디어 경로에서 각 비디오의 UTC 업로드 날짜를 사용합니다. Bulk OSS 데이터 전송은 aliyuncs.com 엔드포인트가 필요합니다.

프라이빗 미디어 file_url 값은 저장 SDK 또는 그 공급자로부터 서명 URL가 필요합니다. FlashData 키는 버킷 액세스 권한을 부여하지 않습니다. 선택적 메타데이터 동반자 파일은 미디어 옆에 저장됩니다. 납품 화물은 delivery.retryCount에서 나타납니다.

Data 개체 레이아웃
<prefix>/<source>/<bulkId>/results/part-NNNNNNNN.jsonl.gz
<prefix>/<source>/<bulkId>/manifest.json

웹훅을 완료

공공 HTTPS callback_url 외부 옵션 배치. Bulk는 나타날을 게시 한 후만 완료합니다. 실패하거나 취소 된 작업을 위해 per-video 이벤트 및 완료 이벤트를 보내지 않습니다. 낙하로 상태 오염을 지키십시오.

  1. Persist 및 deduplicate delivery_id, 다음 2xx를 신속하게 반환합니다. 배달 backoff와 함께 8 배까지.
  2. 이벤트가 취소되지 않습니다. 저장된 영수증에 일치 id 및 소스; 쿼팅 retrieval 전에 인증 된 관리 API를 통해 완료 확인. 인증되지 않은 이벤트에서 URLs를 무시합니다.
콜백으로 요청하기
{
  "source": "youtube_metadata",
  "options": {
    "include_formats": false,
    "include_chapters": false
  },
  "callback_url": "https://your-app.example/webhooks/flashdata"
}
완료 이벤트 · illustrative
{
  "delivery_id": "bulk-completion:bulk_EXAMPLE123",
  "id": "bulk_EXAMPLE123",
  "source": "youtube_metadata",
  "status": "completed",
  "links": [
    {
      "rel": "self",
      "href": "https://api.flashdata.dev/v2/bulk-jobs/bulk_EXAMPLE123",
      "method": "GET"
    },
    {
      "rel": "results",
      "href": "https://api.flashdata.dev/v2/bulk-jobs/bulk_EXAMPLE123/results",
      "method": "GET"
    }
  ]
}

Schema 정의

BulkJobCreated

BulkJobCreated
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "job",
    "upload"
  ],
  "properties": {
    "job": {
      "$ref": "#/components/schemas/BulkJob"
    },
    "upload": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "href",
        "method",
        "expiresAt",
        "contentType"
      ],
      "properties": {
        "href": {
          "type": "string",
          "format": "uri"
        },
        "method": {
          "type": "string",
          "const": "PUT"
        },
        "expiresAt": {
          "type": "string",
          "format": "date-time"
        },
        "contentType": {
          "type": "string",
          "const": "text/plain; charset=utf-8"
        }
      }
    }
  }
}

BulkJob

BulkJob
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "id",
    "source",
    "status",
    "input",
    "counts",
    "delivery",
    "pauseReason",
    "error",
    "createdAt",
    "startedAt",
    "completedAt",
    "expiresAt",
    "links"
  ],
  "properties": {
    "id": {
      "type": "string",
      "pattern": "^bulk_[A-Za-z0-9_-]{8,}$"
    },
    "source": {
      "type": "string",
      "enum": [
        "youtube_metadata",
        "youtube_transcript",
        "youtube_captions",
        "youtube_trainability",
        "youtube_download"
      ]
    },
    "status": {
      "type": "string",
      "enum": [
        "awaiting_upload",
        "running",
        "paused",
        "finalizing",
        "completed",
        "failed",
        "cancelled"
      ]
    },
    "input": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "bytes",
        "complete",
        "scannedBytes",
        "scannedLines"
      ],
      "properties": {
        "bytes": {
          "type": "integer",
          "minimum": 0
        },
        "complete": {
          "type": "boolean"
        },
        "scannedBytes": {
          "type": "integer",
          "minimum": 0
        },
        "scannedLines": {
          "type": "integer",
          "minimum": 0
        }
      }
    },
    "counts": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "accepted",
        "completed",
        "failed",
        "invalid",
        "results"
      ],
      "properties": {
        "accepted": {
          "type": "integer",
          "minimum": 0
        },
        "completed": {
          "type": "integer",
          "minimum": 0
        },
        "failed": {
          "type": "integer",
          "minimum": 0
        },
        "invalid": {
          "type": "integer",
          "minimum": 0
        },
        "results": {
          "type": "integer",
          "minimum": 0
        }
      }
    },
    "pauseReason": {
      "type": [
        "string",
        "null"
      ]
    },
    "delivery": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "customerStorage",
        "storageType",
        "uploadedParts",
        "retryCount"
      ],
      "properties": {
        "customerStorage": {
          "type": "boolean"
        },
        "storageType": {
          "type": [
            "string",
            "null"
          ],
          "enum": [
            "s3",
            "s3_compatible",
            "oss",
            "gcs",
            "azure",
            "cos",
            "bos",
            "tos",
            null
          ]
        },
        "uploadedParts": {
          "type": "integer",
          "minimum": 0
        },
        "retryCount": {
          "type": "integer",
          "minimum": 0
        }
      }
    },
    "error": {
      "oneOf": [
        {
          "type": "null"
        },
        {
          "type": "object",
          "additionalProperties": false,
          "required": [
            "code",
            "detail"
          ],
          "properties": {
            "code": {
              "type": "string"
            },
            "detail": {
              "type": [
                "string",
                "null"
              ]
            }
          }
        }
      ]
    },
    "createdAt": {
      "type": "string",
      "format": "date-time"
    },
    "startedAt": {
      "type": [
        "string",
        "null"
      ],
      "format": "date-time"
    },
    "completedAt": {
      "type": [
        "string",
        "null"
      ],
      "format": "date-time"
    },
    "expiresAt": {
      "type": [
        "string",
        "null"
      ],
      "format": "date-time"
    },
    "links": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/JobLink"
      }
    }
  }
}

BulkJobPage

BulkJobPage
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "data",
    "pagination"
  ],
  "properties": {
    "data": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/BulkJob"
      }
    },
    "pagination": {
      "$ref": "#/components/schemas/Pagination"
    }
  }
}

BulkJobResponse

BulkJobResponse
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "job"
  ],
  "properties": {
    "job": {
      "$ref": "#/components/schemas/BulkJob"
    }
  }
}

CreateBulkJobRequest

CreateBulkJobRequest
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "source"
  ],
  "properties": {
    "source": {
      "type": "string",
      "enum": [
        "youtube_metadata",
        "youtube_transcript",
        "youtube_captions",
        "youtube_trainability",
        "youtube_download"
      ]
    },
    "options": {
      "type": "object",
      "additionalProperties": true,
      "description": "Reused for every ID. Metadata accepts include_formats and include_chapters. Transcript and captions accept language (one code or an array of 1–10 distinct codes) and auto (applies to all requested languages). Omit language to prefer en-orig, fall back to en, and return one track. With auto=true, each requested code tries its -orig track first, then the plain code. Explicit -orig codes and auto=false stay exact. languageCode identifies the selected track; requestedLanguageCode is included when it differs from the requested code. A language array returns tracks and per-language errors for each video with at least one retrieved track. If no track is retrieved, the video job fails and its reserved credits are refunded. Bulk exports use one JSONL record per video. Trainability accepts no source options. These four data sources optionally accept result_storage. Supported storage_type values are s3, s3_compatible, oss, gcs, azure, cos, bos, and tos. storage_url is the bucket name (Azure container name); object_prefix is optional. S3, S3-compatible, OSS, COS, BOS, and TOS use access_key and secret_key. S3-compatible and OSS also require a public HTTPS endpoint_url. COS, BOS, and TOS require region and use fixed provider endpoints. COS bucket names include the APPID. BOS S3-compatible HTTPS delivery supports bj, su, and hkg. GCS requires service_account with project_id, client_email, and private_key. Azure requires account_name and a container SAS sas_token with write permission. Default object_prefix is YYYYMMDD, frozen to the UTC bulk creation date. Files are written to <prefix>/<source>/<bulkId>/results/part-NNNNNNNN.jsonl.gz; manifest.json in the same bulk directory is written last. Each JSONL row includes its input index and completed, failed, or invalid status. Internal R2 results remain available through the result links for 24 hours. Download accepts the normal YouTube download parameters, requires customer storage, and does not permit browser_delivery. Download storage supports the same eight provider types and credential shapes listed above under the storage field. Download storage may include object_prefix; YYYYMMDD tokens resolve to the UTC upload date, while literal prefixes are unchanged."
    },
    "callback_url": {
      "type": "string",
      "format": "uri",
      "maxLength": 2048,
      "description": "Optional public HTTPS endpoint notified once after manifest publication."
    }
  }
}

JobLink

JobLink
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "rel",
    "href",
    "method"
  ],
  "properties": {
    "rel": {
      "type": "string",
      "enum": [
        "self",
        "results",
        "content",
        "download"
      ]
    },
    "href": {
      "type": "string",
      "format": "uri"
    },
    "method": {
      "type": "string",
      "const": "GET"
    },
    "expires_at": {
      "type": "string",
      "format": "date-time"
    },
    "filename": {
      "type": "string"
    },
    "content_type": {
      "type": "string"
    },
    "size_bytes": {
      "type": "integer",
      "minimum": 1
    }
  }
}

Pagination

Pagination
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "hasMore",
    "limit"
  ],
  "properties": {
    "nextCursor": {
      "type": [
        "string",
        "null"
      ]
    },
    "previousCursor": {
      "type": [
        "string",
        "null"
      ]
    },
    "hasMore": {
      "type": "boolean"
    },
    "limit": {
      "type": "integer",
      "minimum": 1,
      "maximum": 100
    }
  }
}

Problem

Problem
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "type",
    "title",
    "status",
    "code",
    "requestId"
  ],
  "properties": {
    "type": {
      "type": "string",
      "format": "uri-reference"
    },
    "title": {
      "type": "string"
    },
    "status": {
      "type": "integer",
      "minimum": 400,
      "maximum": 599
    },
    "code": {
      "type": "string",
      "pattern": "^[a-z0-9_]+$"
    },
    "detail": {
      "type": "string"
    },
    "requestId": {
      "type": "string",
      "pattern": "^req_"
    },
    "fieldErrors": {
      "type": "array",
      "items": {
        "$ref": "#/components/schemas/FieldError"
      }
    }
  }
}

FieldError

FieldError
{
  "type": "object",
  "additionalProperties": false,
  "required": [
    "field",
    "code",
    "message"
  ],
  "properties": {
    "field": {
      "type": "string"
    },
    "code": {
      "type": "string"
    },
    "message": {
      "type": "string"
    }
  }
}

UpdateBulkJobRequest

UpdateBulkJobRequest
{
  "type": "object",
  "additionalProperties": false,
  "minProperties": 1,
  "properties": {
    "options": {
      "type": "object",
      "additionalProperties": true,
      "description": "Partial option update. Nested storage fields are merged so unchanged credentials do not need to be resent. Data result_storage fields are merged the same way. After all IDs have been scanned, a paused data bulk job accepts credential updates only: access_key and secret_key, GCS service_account, or Azure sas_token, depending on the storage type. The complete merged configuration is validated before it is stored."
    },
    "callback_url": {
      "type": [
        "string",
        "null"
      ],
      "format": "uri",
      "maxLength": 2048,
      "description": "Replacement completion callback, or null to remove the callback."
    }
  }
}