Code Examples

Copy, paste, and build

Python

Fetch a transcript and print each segment with its timestamp:

Python
import requests

API_KEY = "2yt_your_key_here"
VIDEO_ID = "dQw4w9WgXcQ"

response = requests.get(
    "https://2outube.com/api/v1/transcript",
    params={"video_id": VIDEO_ID},
    headers={"Authorization": f"Bearer {API_KEY}"}
)

data = response.json()
for segment in data["segments"]:
    print(f"[{segment['start']:.1f}s] {segment['text']}")

JavaScript

Works in Node.js, Deno, Bun, and Cloudflare Workers:

JavaScript
const apiKey = "2yt_your_key_here";
const videoId = "dQw4w9WgXcQ";

const response = await fetch(
  `https://2outube.com/api/v1/transcript?video_id=${videoId}`,
  { headers: { Authorization: `Bearer ${apiKey}` } }
);

const data = await response.json();
data.segments.forEach(seg =>
  console.log(`[${seg.start.toFixed(1)}s] ${seg.text}`)
);

LangChain Integration

Load YouTube transcripts as documents for RAG pipelines:

Python — LangChain
from langchain.document_loaders import TextLoader
import requests

def load_youtube_transcript(video_id, api_key):
    resp = requests.get(
        "https://2outube.com/api/v1/transcript",
        params={"video_id": video_id},
        headers={"Authorization": f"Bearer {api_key}"}
    )
    data = resp.json()
    text = " ".join(seg["text"] for seg in data["segments"])
    return text

# Usage in a RAG pipeline
transcript = load_youtube_transcript("dQw4w9WgXcQ", "2yt_...")
# Feed `transcript` into your LangChain chain or vector store

Error Handling

Handle common error cases gracefully:

Python
import time
import requests

url = "https://2outube.com/api/v1/transcript"
headers = {"Authorization": f"Bearer {API_KEY}"}
params = {"video_id": VIDEO_ID}

response = requests.get(url, headers=headers, params=params)

if response.status_code == 200:
    data = response.json()
    print(f"Got {len(data['segments'])} segments")
elif response.status_code == 401:
    print("Invalid API key")
elif response.status_code == 402:
    print("Credits exhausted - upgrade at https://2outube.com/api#pricing")
elif response.status_code == 404:
    print("No transcript available for this video")
elif response.status_code == 429:
    retry_after = response.headers.get("Retry-After", 60)
    time.sleep(int(retry_after))
else:
    print(f"Error {response.status_code}: {response.text}")

Batch Processing

Fetch transcripts for multiple videos with rate limit handling:

Python
import time
import requests

API_KEY = "2yt_your_key_here"
VIDEO_IDS = ["dQw4w9WgXcQ", "9bZkp7q19f0", "kJQP7kiw5Fk"]

for vid in VIDEO_IDS:
    resp = requests.get(
        "https://2outube.com/api/v1/transcript",
        params={"video_id": vid},
        headers={"Authorization": f"Bearer {API_KEY}"}
    )
    if resp.status_code == 429:
        time.sleep(int(resp.headers.get("Retry-After", 60)))
        continue
    data = resp.json()
    credits = resp.headers.get("X-Credits-Remaining")
    print(f"[{vid}] {len(data.get('segments', []))} segments | {credits} credits left")
    time.sleep(1)  # Be polite

cURL

Quick one-liners for the terminal:

Terminal
# Fetch transcript
$ curl -s -H "Authorization: Bearer 2yt_..." \
  "https://2outube.com/api/v1/transcript?video_id=dQw4w9WgXcQ" | jq .

# Chat about a video
$ curl -s -X POST -H "Authorization: Bearer 2yt_..." \
  -H "Content-Type: application/json" \
  -d '{"video_id": "dQw4w9WgXcQ", "message": "Summarize this video"}' \
  "https://2outube.com/api/v1/chat" | jq .

# Check credits
$ curl -s -H "Authorization: Bearer 2yt_..." \
  "https://2outube.com/api/v1/me" | jq .credits_remaining

AI Chat

Ask questions about any video. The AI reads the transcript and responds with timestamped references:

Python
import requests

API_KEY = "2yt_your_key_here"
VIDEO_ID = "dQw4w9WgXcQ"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# First question
resp = requests.post("https://2outube.com/api/v1/chat",
    headers=HEADERS,
    json={"video_id": VIDEO_ID, "message": "Summarize this video"}
)
answer = resp.json()
print(answer["response"])

# Follow-up with conversation history
resp2 = requests.post("https://2outube.com/api/v1/chat",
    headers=HEADERS,
    json={
        "video_id": VIDEO_ID,
        "message": "What about the second topic?",
        "conversation_history": [
            {"role": "user", "content": "Summarize this video"},
            {"role": "assistant", "content": answer["response"]}
        ]
    }
)
print(resp2.json()["response"])
JavaScript
const apiKey = "2yt_your_key_here";
const videoId = "dQw4w9WgXcQ";

const response = await fetch("https://2outube.com/api/v1/chat", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${apiKey}`,
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    video_id: videoId,
    message: "What are the key takeaways?"
  })
});

const data = await response.json();
console.log(data.response);
console.log(`Credits remaining: ${data.credits.remaining}`);

Need something specific?

Check the full API reference or see how we compare to alternatives