Code Examples
Complete code examples in cURL, Python, and JavaScript for all API endpoints.
Each example shows implementations in cURL, Python (using requests), and JavaScript (using fetch).
Get Transcript
Fetch a transcript for a YouTube video with optional language and format parameters.
cURL
# Get transcript in JSON format (default)
curl -X GET "https://api.fetchtranscript.com/v1/transcripts/dQw4w9WgXcQ" \
-H "Authorization: Bearer yt_your_api_key"
# Get transcript in plain text
curl -X GET "https://api.fetchtranscript.com/v1/transcripts/dQw4w9WgXcQ?format=text" \
-H "Authorization: Bearer yt_your_api_key"
# Get transcript in SRT format
curl -X GET "https://api.fetchtranscript.com/v1/transcripts/dQw4w9WgXcQ?format=srt" \
-H "Authorization: Bearer yt_your_api_key"
# Get Spanish transcript
curl -X GET "https://api.fetchtranscript.com/v1/transcripts/dQw4w9WgXcQ?lang=es" \
-H "Authorization: Bearer yt_your_api_key"Python
import requests
API_KEY = "yt_your_api_key"
BASE_URL = "https://api.fetchtranscript.com/v1"
headers = {
"Authorization": f"Bearer {API_KEY}"
}
# Get transcript in JSON format
def get_transcript(video_id, lang="en", format="json"):
response = requests.get(
f"{BASE_URL}/transcripts/{video_id}",
headers=headers,
params={"lang": lang, "format": format}
)
response.raise_for_status()
return response.json()
# Example usage
transcript = get_transcript("dQw4w9WgXcQ")
print(f"Language: {transcript['language']}")
print(f"Full text: {transcript['text'][:200]}...")
# With segments
for segment in transcript["segments"][:5]:
print(f"[{segment['start']:.1f}s] {segment['text']}")
# Access video metadata (included in response)
if transcript.get("metadata"):
print(f"Video: {transcript['metadata']['title']}")
print(f"Channel: {transcript['metadata']['author']}")JavaScript
const API_KEY = "yt_your_api_key";
const BASE_URL = "https://api.fetchtranscript.com/v1";
async function getTranscript(videoId, lang = "en", format = "json") {
const params = new URLSearchParams({ lang, format });
const response = await fetch(
`${BASE_URL}/transcripts/${videoId}?${params}`,
{
headers: {
"Authorization": `Bearer ${API_KEY}`
}
}
);
if (!response.ok) {
const error = await response.json();
throw new Error(error.message);
}
return response.json();
}
// Example usage
const transcript = await getTranscript("dQw4w9WgXcQ");
console.log(`Language: ${transcript.language}`);
console.log(`Segments: ${transcript.segments.length}`);
// Access video metadata (included in response)
if (transcript.metadata) {
console.log(`Video: ${transcript.metadata.title}`);
console.log(`Channel: ${transcript.metadata.author}`);
}List Available Languages
Get all available transcript languages for a video.
cURL
curl -X GET "https://api.fetchtranscript.com/v1/transcripts/dQw4w9WgXcQ/languages" \
-H "Authorization: Bearer yt_your_api_key"Python
def get_languages(video_id):
response = requests.get(
f"{BASE_URL}/transcripts/{video_id}/languages",
headers=headers
)
response.raise_for_status()
return response.json()
# Example usage
languages = get_languages("dQw4w9WgXcQ")
for lang in languages["languages"]:
print(f"{lang['language']} ({lang['language_code']})")
print(f" Auto-generated: {lang['is_generated']}")JavaScript
async function getLanguages(videoId) {
const response = await fetch(
`${BASE_URL}/transcripts/${videoId}/languages`,
{ headers: { "Authorization": `Bearer ${API_KEY}` } }
);
return response.json();
}
const { languages } = await getLanguages("dQw4w9WgXcQ");
languages.forEach(lang => {
console.log(`${lang.language} (${lang.language_code})`);
});Get Video Metadata
Fetch metadata for a YouTube video.
cURL
curl -X GET "https://api.fetchtranscript.com/v1/videos/dQw4w9WgXcQ" \
-H "Authorization: Bearer yt_your_api_key"Python
def get_video(video_id):
response = requests.get(
f"{BASE_URL}/videos/{video_id}",
headers=headers
)
response.raise_for_status()
return response.json()
# Example usage
video = get_video("dQw4w9WgXcQ")
print(f"Title: {video['title']}")
print(f"Channel: {video['channel_name']}")
print(f"Views: {video['view_count']:,}")
print(f"Duration: {video['duration']} seconds")JavaScript
async function getVideo(videoId) {
const response = await fetch(
`${BASE_URL}/videos/${videoId}`,
{ headers: { "Authorization": `Bearer ${API_KEY}` } }
);
return response.json();
}
const video = await getVideo("dQw4w9WgXcQ");
console.log(`Title: ${video.title}`);
console.log(`Views: ${video.view_count.toLocaleString()}`);Get Video Comments
Fetch comments for a YouTube video with pagination.
cURL
# Get first 100 comments (default)
curl -X GET "https://api.fetchtranscript.com/v1/videos/dQw4w9WgXcQ/comments" \
-H "Authorization: Bearer yt_your_api_key"
# Get 50 comments
curl -X GET "https://api.fetchtranscript.com/v1/videos/dQw4w9WgXcQ/comments?limit=50" \
-H "Authorization: Bearer yt_your_api_key"Python
def get_comments(video_id, limit=100):
response = requests.get(
f"{BASE_URL}/videos/{video_id}/comments",
headers=headers,
params={"limit": limit}
)
response.raise_for_status()
return response.json()
# Example usage
result = get_comments("dQw4w9WgXcQ", limit=50)
print(f"Total comments: {result['total_count']}")
for comment in result["comments"][:5]:
print(f"{comment['author']}: {comment['text'][:50]}...")JavaScript
async function getComments(videoId, limit = 100) {
const response = await fetch(
`${BASE_URL}/videos/${videoId}/comments?limit=${limit}`,
{ headers: { "Authorization": `Bearer ${API_KEY}` } }
);
return response.json();
}
const { comments, total_count } = await getComments("dQw4w9WgXcQ");
console.log(`Total: ${total_count} comments`);List Channel Videos
Get videos from a YouTube channel with pagination.
cURL
# Using @handle
curl -X GET "https://api.fetchtranscript.com/v1/channels/@mkbhd/videos" \
-H "Authorization: Bearer yt_your_api_key"
# Using channel ID with pagination
curl -X GET "https://api.fetchtranscript.com/v1/channels/UCBcRF18a7Qf58cCRy5xuWwQ/videos?limit=10&offset=0" \
-H "Authorization: Bearer yt_your_api_key"
# Include Shorts
curl -X GET "https://api.fetchtranscript.com/v1/channels/@mkbhd/videos?include_shorts=true" \
-H "Authorization: Bearer yt_your_api_key"Python
def get_channel_videos(channel_id, limit=30, offset=0, include_shorts=False):
response = requests.get(
f"{BASE_URL}/channels/{channel_id}/videos",
headers=headers,
params={
"limit": limit,
"offset": offset,
"include_shorts": include_shorts
}
)
response.raise_for_status()
return response.json()
# Paginate through all videos
def get_all_videos(channel_id):
all_videos = []
offset = 0
limit = 100
while True:
result = get_channel_videos(channel_id, limit=limit, offset=offset)
all_videos.extend(result["videos"])
if not result["has_more"]:
break
offset += limit
return all_videos
videos = get_all_videos("@mkbhd")
print(f"Total videos: {len(videos)}")JavaScript
async function getChannelVideos(channelId, limit = 30, offset = 0) {
const params = new URLSearchParams({
limit: limit.toString(),
offset: offset.toString()
});
const response = await fetch(
`${BASE_URL}/channels/${channelId}/videos?${params}`,
{ headers: { "Authorization": `Bearer ${API_KEY}` } }
);
return response.json();
}
const { videos, has_more } = await getChannelVideos("@mkbhd");
console.log(`Got ${videos.length} videos`);Search Videos
Search YouTube videos by query.
cURL
curl -X GET "https://api.fetchtranscript.com/v1/search?q=machine%20learning&limit=20" \
-H "Authorization: Bearer yt_your_api_key"Python
def search_videos(query, limit=10):
response = requests.get(
f"{BASE_URL}/search",
headers=headers,
params={"q": query, "limit": limit}
)
response.raise_for_status()
return response.json()
# Example usage
results = search_videos("machine learning tutorial", limit=20)
print(f"Found {results['total_results']} results")
for video in results["results"]:
print(f"- {video['title']}")JavaScript
async function searchVideos(query, limit = 10) {
const params = new URLSearchParams({ q: query, limit: limit.toString() });
const response = await fetch(
`${BASE_URL}/search?${params}`,
{ headers: { "Authorization": `Bearer ${API_KEY}` } }
);
return response.json();
}
const { results } = await searchVideos("machine learning");
results.forEach(video => console.log(video.title));Complete Example: Batch Processing
Here is a complete example that fetches transcripts for all videos from a channel.
Python
import requests
import time
API_KEY = "yt_your_api_key"
BASE_URL = "https://api.fetchtranscript.com/v1"
headers = {"Authorization": f"Bearer {API_KEY}"}
def get_channel_videos(channel_id, limit=100):
"""Get all videos from a channel."""
videos = []
offset = 0
while True:
response = requests.get(
f"{BASE_URL}/channels/{channel_id}/videos",
headers=headers,
params={"limit": limit, "offset": offset}
)
response.raise_for_status()
data = response.json()
videos.extend(data["videos"])
if not data["has_more"]:
break
offset += limit
time.sleep(0.5) # Respect rate limits
return videos
def get_transcript(video_id, lang="en"):
"""Get transcript for a video."""
try:
response = requests.get(
f"{BASE_URL}/transcripts/{video_id}",
headers=headers,
params={"lang": lang}
)
response.raise_for_status()
return response.json()
except requests.HTTPError as e:
if e.response.status_code == 404:
return None # No transcript available
raise
def batch_get_transcripts(channel_id):
"""Get transcripts for all videos from a channel."""
print(f"Fetching videos from channel: {channel_id}")
videos = get_channel_videos(channel_id)
print(f"Found {len(videos)} videos")
transcripts = []
for i, video in enumerate(videos):
print(f"Processing {i+1}/{len(videos)}: {video['title'][:50]}...")
transcript = get_transcript(video["video_id"])
if transcript:
transcripts.append({
"video_id": video["video_id"],
"title": video["title"],
"transcript": transcript["text"]
})
time.sleep(0.3) # Respect rate limits
print(f"Successfully fetched {len(transcripts)} transcripts")
return transcripts
# Usage
transcripts = batch_get_transcripts("@mkbhd")