Chuyển đến nội dung
VI
Lấy khóa API
Duyệt tài liệu

Tham chiếu API

API xử lý Bulk

Tạo và điều khiển tập tin dựa trên YouTube làm việc, rồi lấy lại bản kê khai và kết quả là các bộ phận.

Trên trang này

Sân thử API

Chọn một nguồn và sao chép một nguồn đầy đủ Python hay Bash Dòng chảy công việc, một yêu cầu đơn hoặc một phản ứng mẫu. Mã xem thử sân chơi; nó không gửi công việc. Toàn bộ lưu lượng công việc xử lý việc tải lên, kiểm tra trạng thái và thu hồi lại mọi kết quả.

Tham số nguồn

Xây dựng a Bulk lưu công việc

Cục bộ UTF-8 Tập tin, một YouTube ID mỗi dòng, lên đến 2 GiB. Yêu cầu nhập.

Để trống để thử en-orig, sau đó en, và trở lại một dấu vết. Hoặc nhập một mã số hoặc lên đến 10 Mã riêng biệt được tách ra bởi Dấu phẩy.

Theo dõi độ xoay auto

Kết quả

Hãy để việc này lại để lấy kết quả thông qua FlashData API.

Bulk kết nốiThông báo và thẩm tra hoàn tất
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_captions",
    "options": {
        "auto": False,
    },
}

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)
Tạo, tải lên, bắt đầu, theo dõi và lấy lại tất cả các phầnX-API-Key Xác thực

Điểm kết thúc

Mọi điểm kết thúc được dùng https://api.flashdata.dev/v2. Tạo một công việc đờn bà tải lên videoID Tập tin _BAR_bắt đầu màn hình _BAR_ tiềm năng truy cập vào bản kê khai và mọi kết quả.

Phương phápĐường dẫnHành động
POST/v2/bulk-jobsTạo một Bulk công việc
POST/v2/bulk-jobs/{bulkId}/startTải lên và bắt đầu
GET/v2/bulk-jobs/{bulkId}Lấy trạng thái công việc
GET/v2/bulk-jobsLiệt kê các tác vụ
POST/v2/bulk-jobs/{bulkId}/pauseTạm dừng một công việc
PATCH/v2/bulk-jobs/{bulkId}Cập nhật tùy chọn công việc
POST/v2/bulk-jobs/{bulkId}/resumeTiếp tục công việc
DELETE/v2/bulk-jobs/{bulkId}Hủy bỏ công việc
GET/v2/bulk-jobs/{bulkId}/resultsLấy bản kê kết quả
GET/v2/bulk-jobs/{bulkId}/results/{partNumber}Tải về các phần kết quả

Xác thực và nhập

Đặt FLASHDATA_API_KEY tới một phím có quyền truy cập vào nguồn đã chọn. Dùng lại cùng một chìa khóa và tài khoản cho sự sáng tạo, điều khiển và kết quả. Tiến trình xử lý sử dụng sự số dư của tài khoản và giá cả bình thường cho mỗi nguồn. YouTube Download yêu cầu quyền truy cập và options.storage.

Tạo một thư mục làm việc tên là ob-api / và chạy các ví dụ từ nó. Sân chơi đã hoàn tất Python Dòng chảy công việc sử dụng Python 3.10+ thư viện chuẩn; cá nhân Python Ví dụ điểm cuối bên dưới cần thiết yêu cầu; cURL ví dụ dùng Bash, cURL 7.76+, jq và g tiêu. Chọn một ngôn ngữ cho mỗi hành động để bạn không tạo hoặc bắt đầu làm việc lặp lại.

Nhập là một UTF-8 Tập tin có một 11- Hồ sơ. YouTube ID mỗi dòng, lên đến 2 GiB. Sử dụng IDs, không phải URLs. Gỡ bỏ bản sao IDs trước khi tải lên; lặp lại IDs được xử lý riêng biệt.

NguồnTùy chọn chia sẻ
youtube_metadatainclude_formats, include_chapters
youtube_transcriptngôn ngữ, tự động
youtube_captionsngôn ngữ, tự động
youtube_trainabilitytuỳ chọn
youtube_downloadTùy chọn phương tiện và đích lưu trữ
Phụ thuộc Python
python -m pip install requests

Tạo trường cầu xin

Tìm kiếmKiểuSử dụng
sourcestringYêu cầu. Một nguồn hỗ trợ cho mỗi dữ liệu ID.
optionsobjectTùy chọn nguồn chia sẻ. Nguồn dữ liệu có thể đặt result_storage; YouTube Download yêu cầu lưu trữ.
callback_urlstringCông chúng tùy chọn HTTPS Gọi lại sau. Gửi sau khi xuất bản xong.

Tạo một Bulk công việc

Tạo một công việc, tải lên một UTF-8 Tập tin văn bản có một 11- Hồ sơ. YouTube video ID mỗi dòng upload.hrefsau đó gọi cho bắt đầu. Tự tạo ra công việc không bắt đầu xử lý.

Name video-ids.txt và cứu lấy 201 Biên nhận cho bulk-created.json. Giữ biên lai riêng tư và sử dụng lại job.id cho mỗi yêu cầu sau này. Tạo ra một công việc để lại nó trong awaiting_upload; tải lên URL Comment 15 phút

Điểm kết thúc
POST https://api.flashdata.dev/v2/bulk-jobs
X-API-Key: YOUR_API_KEY

Lưu bulk_create.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python bulk_create.py

Đáp ứng và yêu cầu

Trạng thái HTTPNghĩa là
201Bulk công việc được tạo ra với một 15- Phút trực tiếp tải lên URL
401Xác thực cần thiết hay không hợp lệ
422Yêu cầu xác thực thất bại
503Một quan hệ phụ thuộc hay danh mục cần thiết tạm thời không tồn tại
Nội dung yêu cầu
{
  "$ref": "#/components/schemas/CreateBulkJobRequest"
}
201 · application/json
{
  "$ref": "#/components/schemas/BulkJobCreated"
}

Tải lên và bắt đầu

Bắt đầu xử lý việc tải lên UTF-8 video ID tập tin, tới 2 GiB (2147483648 byte). Giữ tập tin không thay đổi sau khi bắt đầu.

Đầu PUT video-ids.txt đến biên lai upload.href có upload.contentTypekhông có X-API-Key. Ví dụ gọi điện chỉ khi tải lên thành công. Giữ tập tin tải lên không thay đổi sau đó.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
Điểm kết thúc
POST https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/start
X-API-Key: YOUR_API_KEY

Lưu bulk_start.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python bulk_start.py

Đáp ứng

Trạng thái HTTPNghĩa là
200Bulk Công việc bắt đầu hay trạng thái nhận diện hiện tại
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
409Tình trạng tài nguyên hoặc xung đột quyền tối thiểu
422Yêu cầu xác thực thất bại
503Một quan hệ phụ thuộc hay danh mục cần thiết tạm thời không tồn tại
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

Lấy trạng thái công việc

Đọc job.statusĐầu vào, tính, pauseReason và sai lầm. Kiểm tra lại ID với sự chậm trễ; hoàn tất nghĩa là bản kê khai được xuất bản, chứ không phải mỗi video đều thành công.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
Điểm kết thúc
GET https://api.flashdata.dev/v2/bulk-jobs/{bulkId}
X-API-Key: YOUR_API_KEY

Lưu bulk_status.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python bulk_status.py

Đáp ứng

Trạng thái HTTPNghĩa là
200Bulk Tình trạng công việc
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

Liệt kê các tác vụ

Câu trả lời chứa dữ liệu và sự tạo hình. Qua pagination.nextCursor là tham số truy vấn con chạy tiếp theo cho đến khi nó là null. Dùng giới hạn từ 1 phải 50; mặc định là 20.

Tham sốĐịa điểmCần thiết
cursorqueryKhông bắt buộc · {"type":"string","maxLength":512}
limitqueryKhông bắt buộc · {"type":"integer","minimum":1,"maximum":50,"default":20}
Điểm kết thúc
GET https://api.flashdata.dev/v2/bulk-jobs
X-API-Key: YOUR_API_KEY

Lưu list_bulk_jobs.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python list_bulk_jobs.py

Đáp ứng

Trạng thái HTTPNghĩa là
200Trang công việc Bulk
401Xác thực cần thiết hay không hợp lệ
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobPage"
}

Tạm dừng một công việc

Tạm dừng việc nộp đơn và đóng gói kết quả. Công việc tồn tại tiếp tục với các thiết lập và cáo buộc ban đầu. Hãy tiếp tục công việc khi sẵn sàng.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
Điểm kết thúc
POST https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/pause
X-API-Key: YOUR_API_KEY

Lưu pause_bulk_job.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python pause_bulk_job.py

Đáp ứng

Trạng thái HTTPNghĩa là
200Công việc lớn tạm dừng hoặc trạng thái nhận diện hiện tại của nó
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

Cập nhật tùy chọn công việc

Cập nhật tùy chọn trong khi chờ tải lên, hoặc tạm dừng trước khi đọc mọi dữ liệu nhập. Công việc tồn tại giữ cho thiết lập của họ. Nếu tạm dừng vẫn đang tiến hành, hãy đợi và thử lại a 409 Trả lời đi. Sau khi đọc tất cả các dữ liệu nhập, chỉ có giấy ủy nhiệm giao hàng mới có thể cập nhật. Đặt callback_url phải null để loại bỏ nó.

Ví dụ này loại bỏ gọi lại hoàn tất. Để thay đổi tùy chọn nguồn, hãy gửi một đối tượng tùy chọn. Tạm dừng đầu tiên và chờ đợi cho các tạm dừng để có hiệu quả; một 409 có nghĩa là cập nhật chưa được áp dụng. Việc tồn tại công việc trẻ em giữ lại những lựa chọn ban đầu của chúng.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
Điểm kết thúc
PATCH https://api.flashdata.dev/v2/bulk-jobs/{bulkId}
X-API-Key: YOUR_API_KEY

Lưu update_bulk_job.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python update_bulk_job.py

Đáp ứng và yêu cầu

Trạng thái HTTPNghĩa là
200Tình trạng khối công việc cập nhật
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
409Tình trạng tài nguyên hoặc xung đột quyền tối thiểu
422Yêu cầu xác thực thất bại
Nội dung yêu cầu
{
  "$ref": "#/components/schemas/UpdateBulkJobRequest"
}
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

Tiếp tục công việc

Sửa pauseReason Đầu tiên, như là thêm tín dụng hoặc cập nhật giấy ủy nhiệm lưu trữ, sau đó tiếp tục như cũ Bulk ID.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
Điểm kết thúc
POST https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/resume
X-API-Key: YOUR_API_KEY

Lưu resume_bulk_job.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python resume_bulk_job.py

Đáp ứng

Trạng thái HTTPNghĩa là
200Trạng thái công việc phụ hiện tại
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

Hủy bỏ công việc

Dừng lại đi. Việc làm tồn tại vẫn có thể finish và nhận tội bình thường của họ. Một công việc bị hủy không xuất bản danh sách cuối cùng.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
Điểm kết thúc
DELETE https://api.flashdata.dev/v2/bulk-jobs/{bulkId}
X-API-Key: YOUR_API_KEY

Lưu cancel_bulk_job.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python cancel_bulk_job.py

Đáp ứng

Trạng thái HTTPNghĩa là
200Trạng thái công việc phụ hiện tại
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
200 · application/json
{
  "$ref": "#/components/schemas/BulkJobResponse"
}

Lấy bản kê kết quả

Theo hướng chuyển tiếp để tải về JSON Hiển thị và sử dụng các liên kết của nó để lấy các tập tin kết quả. Đem về kho lưu trữ đã được ký URLs Không có bạn API Chìa khóa. Kết quả vẫn còn sẵn sàng cho 24 Hàng giờ sau toàn bộ Bulk Công việc hoàn tất.

Xác thực API Yêu cầu trả lại 302 với tiêu đề địa điểm. Lấy đi. HTTPS kho URL trong một yêu cầu riêng biệt không X-API-Key. Ví dụ này cứu được manifest.json. A 409 có nghĩa là kết quả chưa sẵn sàng; 410 Nghĩa là chúng đã hết hạn.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
Điểm kết thúc
GET https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/results
X-API-Key: YOUR_API_KEY

Lưu bulk_manifest.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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))
Chạy từ con số lớn
python bulk_manifest.py

Đáp ứng

Trạng thái HTTPNghĩa là
200JSON Name
302Chuyển hướng về một nơi riêng tư ngắn hạn R2 URL; API Không được chuyển hồ sơ · Location
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
409Tình trạng tài nguyên hoặc xung đột quyền tối thiểu
410Kết quả được duy trì đã hết hạn
200 · application/json
{
  "type": "object",
  "additionalProperties": true
}

Tải về các phần kết quả

Dùng mỗi parts[].number từ manifest.json. Mỗi điểm kết thúc trở về một 302 cho g tiêu đề NDJSON Tập tin; tải về mà không có API Chìa khóa, giảm áp, sau đó phân tích một JSON đối tượng trên một dòng. Hãy tham gia vào chỉ mục dựa trên số không. Ví dụ này thu thập tất cả các bộ phận và giữ cả hai.ndjson.gz và các hồ sơ.ndjson.

Tham sốĐịa điểmCần thiết
bulkIdpathBắt buộc · {"type":"string","pattern":"^bulk_[A-Za-z0-9_-]{8,}$"}
partNumberpathBắt buộc · {"type":"integer","minimum":0}
Điểm kết thúc
GET https://api.flashdata.dev/v2/bulk-jobs/{bulkId}/results/{partNumber}
X-API-Key: YOUR_API_KEY

Lưu bulk_parts.py trong đa chiều / bên cạnh bulk-created.json. Sao chép văn lệnh đầy đủ, rồi chạy lệnh bên dưới nó.

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)))
Chạy từ con số lớn
python bulk_parts.py

Đáp ứng

Trạng thái HTTPNghĩa là
200Gzip- bị nén NDJSON Tải về sau khi chuyển tiếp
302Chuyển hướng về một nơi riêng tư ngắn hạn R2 URL; API Không được chuyển hồ sơ · Location
401Xác thực cần thiết hay không hợp lệ
404Không tìm thấy tài nguyên hay không thuộc về người gọi
409Tình trạng tài nguyên hoặc xung đột quyền tối thiểu
410Kết quả được duy trì đã hết hạn
200 · application/x-ndjson
{
  "type": "string"
}

Trạng thái công việc và sự chú ý

Kết quả vẫn còn sẵn sàng cho 24 Hàng giờ sau toàn bộ Bulk Công việc hoàn tất. Hãy cứu họ trước đi. expiresAt. Phương tiện trong đích của bạn làm theo chính sách lưu trữ của xô. Một công việc hoàn tất có thể bao gồm các video thất bại; counts.invalid ghi chép bị từ chối.

Tình trạngHành động tiếp theo
awaiting_uploadTải lên tập tin và bắt đầu cuộc gọi.
runningCũng như nhau thôi ID với lùi lại; input.complete hiển thị việc quét xong chưa.
pausedĐọc pauseReason, sửa nó, rồi tiếp tục.
finalizingChờ kết quả của việc đóng gói và xuất bản.
completedTải về danh sách và mọi phần. Kiểm tra tình trạng và lỗi của mỗi hàng.
failed / cancelledLỗi kiểm tra và lưu trạng thái. Không có bản kê khai cuối cùng được xuất bản.

Giao hàng

Dùng sân chơi để cấu hình nhà cung cấp và xem thử trường yêu cầu chính xác. Chứng nhận khách hàng thuộc về vật lưu trữ đã được chọn; X-API-Key Chỉ xác thực FlashData API yêu cầu.

NguồnTạo trường yêu cầuGiao hàng
Siêu dữ liệu, ghi chép, chú thích, kiểm tra bằng láioptions.result_storageTùy anh thôi. Bản sao NDJSON kết quả là các bộ phận và một bản kê khai cho xô của bạn.
youtube_downloadoptions.storageYêu cầu. Giao truyền thông cho xô nước của bạn; result_storage và browser_delivery không được chấp nhận.

Tìm các tập tin đã gửi

Bản liệt kê dữ liệu được viết cuối cùng và liệt kê các phím đối tượng, kích cỡ và SHA-256 Quản lý chi phiếu. Nó khác với FlashData Danh sách nào API Giá trị href. YYYYMMD trong các đường dẫn dữ liệu sử dụng UTC Bulk Ngày tạo; trong phương tiện truyền thông, nó sử dụng mỗi video UTC upload ngày. Bulk Cần thiết giao dữ liệu OSS aliyuncs.com điểm cuối.

Truyền thông cá nhân file_url giá trị cần lưu trữ của bạn SDK hay chữ ký URL từ nhà cung cấp đó. A FlashData Chìa khóa không cho phép xô vào. Các tập tin đồng bộ với siêu dữ liệu tùy chọn được cất bên cạnh các tập tin. Các đệ quy giao hàng xuất hiện delivery.retryCount.

Name
<prefix>/<source>/<bulkId>/results/part-NNNNNNNN.jsonl.gz
<prefix>/<source>/<bulkId>/manifest.json

Nhận một trình điều khiển hoàn tất

Hãy công khai HTTPS callback_url những lựa chọn bên ngoài. Bulk gửi tin hoàn tất chỉ sau khi xuất bản bản danh sách; nó không gửi sự kiện per-video và không có sự kiện hoàn thành cho thất bại hoặc hủy bỏ công việc. Cứ tiếp tục thăm dò tình trạng như một hậu quả.

  1. Kiên trì và phức tạp delivery_idSau đó trả lại 2x ngay lập tức. Việc giao hàng được thu hồi lại đến 8 lần với việc rút lui.
  2. Những sự kiện không được ký. Khớp id và nguồn cho biên nhận đã lưu của bạn; xác nhận hoàn tất thông qua bộ quản lý xác thực API trước khi thu hồi lại. Bỏ qua URLs từ một sự kiện không xác định.
Tạo yêu cầu với một gọi lại
{
  "source": "youtube_metadata",
  "options": {
    "include_formats": false,
    "include_chapters": false
  },
  "callback_url": "https://your-app.example/webhooks/flashdata"
}
Sự kiện gõ xong
{
  "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"
    }
  ]
}

Định nghĩa sơ đồ

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."
    }
  }
}