Chuyển đến nội dung

YouTube Chú thích video API (V1) ​

GET
Tình trạng sức khỏe API
Ổn định Có sẵn Hạn chế Hầu như không có sẵn Không có dữ liệu
Đang tải tình trạng sức khỏe...

Lấy lại các bản ghi chú có sẵn cho video trên YouTube hoặc yêu cầu bản ghi chú dưới định dạng SRT, XML, JSON3 hoặc văn bản đơn giản. Sử dụng để hỗ trợ việc chuyển đổi âm thanh, tính khả dụng, dịch thuật hoặc phân tích văn bản.

Tham số ​

Tên Vị trí Kiểu dữ liệu Bắt buộc Mặc định Mô tả
token query string Đúng - Token truy cập cho dịch vụ API này.
videoId query string Đúng - Định danh duy nhất của một video trên YouTube.
languageCode query string Không Mã ngôn ngữ cho chú thích, như en, zh-Hans, hoặc a.en. Để trống để lấy các bản ghi chú có sẵn.
format query string Không srt Định dạng đầu ra của chú thích.


Các giá trị có sẵn:

- srt: Định dạng chú thích SubRip với dấu thời gian

- xml: Định dạng chú thích XML gốc

- json3: Cấu trúc chú thích JSON gốc của YouTube

- txt: Văn bản thuần túy không có dấu thời gian

Ví dụ mã hóa ​

bash
curl --max-time 120 -X GET 'https://api.justoneapi.com/api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE'
text
Tôi muốn sử dụng API "Chú thích video (V1)" từ JustOneAPI.
URL cơ sở: https://api.justoneapi.com.
Đường dẫn API: /api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE
Điểm cuối API: BASE_URL + /api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE
Phương thức HTTP: GET
Xác thực: Thêm tham số "token" vào URL.
Định nghĩa OpenAPI: https://docs.justoneapi.com/openapi/youtube/video-captions-v1-vi.json

Tham số:
- token (query): Token truy cập cho dịch vụ API này. (Bắt buộc)
- videoId (query): Định danh duy nhất của một video trên YouTube. (Bắt buộc)
- languageCode (query): Mã ngôn ngữ cho chú thích, như en, zh-Hans, hoặc a.en. Để trống để lấy các bản ghi chú có sẵn.
- format (query): Định dạng đầu ra của chú thích.

Các giá trị có sẵn:
- `srt`: Định dạng chú thích SubRip với dấu thời gian
- `xml`: Định dạng chú thích XML gốc
- `json3`: Cấu trúc chú thích JSON gốc của YouTube
- `txt`: Văn bản thuần túy không có dấu thời gian

Định dạng trả về: Xử lý an toàn phản hồi JSON hoặc văn bản dựa trên Content-Type thực tế.

Xử lý phản hồi và mã lỗi:
1. Đọc kết quả xử lý từ trường "code" trong nội dung phản hồi (mã 0 là thành công).
2. Thời gian chờ đề xuất: 120 giây. Nếu 120 giây quá dài, hãy dành ít nhất 60 giây. Một số yêu cầu có thể hết thời gian chờ trước khi có kết quả.
3. Mã kết quả:
   - 0: Thành công
   - 100: Token không hợp lệ hoặc đã bị vô hiệu hóa
   - 301: Không lấy được dữ liệu. Hãy thử lại.
   - 302: Vượt giới hạn tần suất gọi
   - 303: Vượt hạn mức trong ngày
   - 400: Tham số không hợp lệ
   - 500: Lỗi nội bộ máy chủ
   - 600: Không có quyền truy cập
   - 601: Không đủ số dư
   - 602: Đã chạm giới hạn ngân sách token
4. Mã 601 nghĩa là số dư dùng chung của tài khoản không đủ. Mã 602 nghĩa là token API đã chạm giới hạn ngân sách tích lũy riêng. Việc đặt ngân sách cho token không chuyển tiền khỏi số dư dùng chung.

Xin hãy giúp tôi viết một script bằng ngôn ngữ lập trình yêu thích để gọi API này và xử lý phản hồi.
python
import requests

BASE_URL = "https://api.justoneapi.com"  # Được cung cấp bởi các server OpenAPI

url = BASE_URL + "/api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE"
response = requests.get(url, timeout=120)
print(response.status_code)
if response.content:
    content_type = response.headers.get("content-type", "").lower()
    if "json" in content_type:
        try:
            print(response.json())
        except ValueError:
            print(response.text)
    elif content_type.startswith("text/") or "xml" in content_type or content_type.split(";", 1)[0].strip() in {"application/javascript", "application/x-www-form-urlencoded", "application/graphql"}:
        print(response.text)
    else:
        with open("response.bin", "wb") as output:
            output.write(response.content)
        print(f"Saved {len(response.content)} bytes to response.bin")
js
const BASE_URL = "https://api.justoneapi.com"; // Được cung cấp bởi các server OpenAPI
const url = BASE_URL + "/api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE";

const response = await fetch(url, {
  method: "GET",
  signal: AbortSignal.timeout(120000)
});
console.log(response.status);
const responseBytes = await response.arrayBuffer();
if (responseBytes.byteLength) {
  const contentType = (response.headers.get("content-type") || "").toLowerCase();
  const mediaType = contentType.split(";", 1)[0].trim();
  const textual = contentType.startsWith("text/") || contentType.includes("json") || contentType.includes("xml") || ["application/javascript", "application/x-www-form-urlencoded", "application/graphql"].includes(mediaType);
  if (textual) {
    const responseText = new TextDecoder().decode(responseBytes);
    let data = responseText;
    if (contentType.includes("json")) {
      try { data = JSON.parse(responseText); } catch { /* Keep the raw body. */ }
    }
    console.log(data);
  } else {
    console.log(`Received ${responseBytes.byteLength} binary bytes`);
  }
}
java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class Main {
    public static void main(String[] args) throws Exception {
        final String BASE_URL = "https://api.justoneapi.com"; // Được cung cấp bởi các server OpenAPI
        final String url = BASE_URL + "/api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE";

        HttpClient client = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(120)).build();
        HttpRequest.Builder builder = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .timeout(Duration.ofSeconds(120))
            .method("GET", HttpRequest.BodyPublishers.noBody());

        HttpRequest request = builder.build();

        HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
        System.out.println(response.statusCode());
        String contentType = response.headers().firstValue("content-type").orElse("").toLowerCase();
        String mediaType = contentType.split(";", 2)[0].trim();
        if (contentType.startsWith("text/") || contentType.contains("json") || contentType.contains("xml") || mediaType.equals("application/javascript") || mediaType.equals("application/x-www-form-urlencoded") || mediaType.equals("application/graphql")) {
            System.out.println(new String(response.body(), StandardCharsets.UTF_8));
        } else {
            Files.write(Path.of("response.bin"), response.body());
            System.out.println("Saved " + response.body().length + " bytes to response.bin");
        }
    }
}
go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
	"net/http"
	"time"
)

const BASE_URL = "https://api.justoneapi.com" // Được cung cấp bởi các server OpenAPI

func main() {
	client := &http.Client{Timeout: 120 * time.Second}
	url := BASE_URL + "/api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE"
	req, _ := http.NewRequest("GET", url, nil)
	resp, _ := client.Do(req)
	defer resp.Body.Close()
	fmt.Println(resp.StatusCode)
	bodyBytes, _ := io.ReadAll(resp.Body)
	contentType := strings.ToLower(resp.Header.Get("Content-Type"))
	mediaType := strings.TrimSpace(strings.SplitN(contentType, ";", 2)[0])
	if strings.HasPrefix(contentType, "text/") || strings.Contains(contentType, "json") || strings.Contains(contentType, "xml") || mediaType == "application/javascript" || mediaType == "application/x-www-form-urlencoded" || mediaType == "application/graphql" {
		fmt.Println(string(bodyBytes))
	} else {
		os.WriteFile("response.bin", bodyBytes, 0600)
		fmt.Printf("Saved %d bytes to response.bin\n", len(bodyBytes))
	}
}
php
<?php
$BASE_URL = 'https://api.justoneapi.com'; // Được cung cấp bởi các server OpenAPI
$url = $BASE_URL . '/api/youtube/get-video-captions/v1?token=YOUR_API_KEY&videoId=VALUE';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$contentType = strtolower((string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE));
curl_close($ch);
echo $status . PHP_EOL;
$mediaType = trim(explode(';', $contentType, 2)[0]);
if (str_starts_with($contentType, 'text/') || str_contains($contentType, 'json') || str_contains($contentType, 'xml') || in_array($mediaType, ['application/javascript', 'application/x-www-form-urlencoded', 'application/graphql'], true)) {
    echo $response;
} else {
    file_put_contents('response.bin', $response);
    echo 'Saved ' . strlen($response) . ' bytes to response.bin' . PHP_EOL;
}

Các trường trong phản hồi ​

Các trường chính trong phản hồi thành công (code = 0).

Đường dẫn trường Kiểu dữ liệu Mô tả
data - Các bản ghi chú phụ hoặc nội dung chú thích có sẵn cho ngôn ngữ được yêu cầu.
data.video_id string Định danh của video trên YouTube.
data.captions array Các bản nhạc có sẵn khi languageCode bị bỏ qua.
data.captions[] object Một bản ghi chú phụ có sẵn.
data.captions[].language_code string Mã ngôn ngữ cần truyền vào languageCode cho bản ghi chú.
data.captions[].language_name string Tên ngôn ngữ được hiển thị cho bản ghi chú.
data.language_code string Mã ngôn ngữ được báo cáo cho bản ghi chú được chọn.
data.language_name string Tên ngôn ngữ được hiển thị cho bản ghi chú được chọn.
data.format string Định dạng nội dung chú thích được báo cáo.
data.content string | object Nội dung chú thích. SRT, XML và TXT trả về văn bản. JSON3 có thể trả về đối tượng với các sự kiện có thời gian.
data.content.events array Các sự kiện có thời gian trong nội dung chú thích JSON3.
data.content.events[] object Một sự kiện chú thích có thời gian.
data.content.events[].tStartMs integer Thời gian bắt đầu sự kiện trong mili giây tính từ đầu video.
data.content.events[].dDurationMs integer Thời lượng của sự kiện chú thích trong mili giây.
data.content.events[].segs array Các đoạn văn bản thuộc về sự kiện.
data.content.events[].segs[] object Một đoạn văn bản trong sự kiện chú thích.
data.content.events[].segs[].utf8 string Nội dung của đoạn văn bản.

Ví dụ phản hồi ​

Đang tải ví dụ phản hồi...