Tools & Extensions

YouTube Transcript API Python: From Installation to Production-Hardened Code (2026)

··10 min read

The three-line snippet works in a Jupyter notebook. It stops working the moment you deploy to a cloud server or run it against more than a handful of videos. This guide covers what comes after the notebook — proxy configuration, retry logic, async patterns, and full error handling for the youtube-transcript-api library (v1.2.4, Python 3.8–3.14) in a production environment.

This article expands on the library section in our main YouTube transcript API guide. If you're starting from scratch and just want to understand the basics first, start there.


Installation and Setup (What the Docs Don't Mention)

The short answer: pip install youtube-transcript-api is the full install. No API key, no Google Cloud project, no headless browser required — which is the primary reason developers choose this library over the official YouTube Data API v3.

pip install youtube-transcript-api

That installs the current stable release (1.2.4 as of January 29, 2026). For production, pin the version in your requirements file:

youtube-transcript-api==1.2.4

The library has no hard external dependencies beyond the Python standard library and requests. What the docs don't mention: the WebshareProxyConfig class (used in every production deployment) lives in youtube_transcript_api.proxies, not the main module. You'll need that import separately when you get to proxy configuration.


Core API: Fetching a Single Transcript

The short answer: The API takes an 11-character video ID (not a full URL), returns a FetchedTranscript object you can iterate over or convert with .to_raw_data(). Auto-generated captions and manually-created captions are both accessible — you don't need to do anything special to get auto-generated transcripts.

from youtube_transcript_api import YouTubeTranscriptApi

ytt_api = YouTubeTranscriptApi()
transcript = ytt_api.fetch("dQw4w9WgXcQ")

Each snippet in the transcript looks like this when accessed via .to_raw_data():

{
    "text": "Never gonna give you up",
    "start": 43.6,
    "duration": 2.1
}

start is in seconds from the beginning of the video. duration is how long that segment is displayed. A full video transcript typically returns dozens to hundreds of these segments depending on video length and caption density.

Auto-generated vs. manually-created captions: The library fetches both without distinction by default. If you need to tell them apart — for quality filtering, for example — use the .list() method, which returns a TranscriptList with metadata including the is_generated flag for each available transcript.

ytt_api = YouTubeTranscriptApi()
transcript_list = ytt_api.list("dQw4w9WgXcQ")
for transcript in transcript_list:
    print(transcript.language, transcript.is_generated)

Language Selection and Fallback Behavior

The short answer: Pass a languages list to .fetch() and the library tries them in order, returning the first match. If none of the listed languages have a transcript, NoTranscriptFound is raised. There is no automatic fallback to English unless you include it in the list.

ytt_api = YouTubeTranscriptApi()

# Try Spanish first, fall back to English
transcript = ytt_api.fetch(
    "VIDEO_ID",
    languages=["es", "en"]
)

If you don't pass languages, the library returns the default transcript for the video — usually English for English-language content, but this isn't guaranteed. For a robust pipeline that needs to handle international content, always be explicit:

ytt_api = YouTubeTranscriptApi()

# For a pipeline that only processes English content
try:
    transcript = ytt_api.fetch(
        video_id,
        languages=["en"]
    )
except NoTranscriptFound:
    # No English transcript — skip or log
    return None

Formatting Transcripts: TextFormatter, JSONFormatter, and Subtitle Formats

The short answer: The raw transcript object is rarely what you want to pass downstream. The library includes formatters that convert to plain text, JSON, SRT, and WebVTT with one import and one method call. TextFormatter strips timestamps and returns a clean string — the most common need for NLP pipelines.

from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api.formatters import TextFormatter, JSONFormatter, SRTFormatter

ytt_api = YouTubeTranscriptApi()
transcript = ytt_api.fetch("VIDEO_ID")

# Plain text — most useful for LLM input, summarization, search indexing
formatter = TextFormatter()
plain_text = formatter.format_transcript(transcript)

# JSON string — useful for storage or API responses
json_formatter = JSONFormatter()
json_text = json_formatter.format_transcript(transcript)

# SRT — for subtitle editing workflows
srt_formatter = SRTFormatter()
srt_text = srt_formatter.format_transcript(transcript)

TextFormatter joins the text segments with spaces and strips timing data entirely. If you're feeding transcripts into an LLM, this is what you want. If you need timestamps preserved — for citation, for video navigation, for training data that includes temporal position — keep the raw transcript object or use SRT/WebVTT format instead.


Proxies in Production: WebshareProxyConfig and What Residential Actually Means

The short answer: Cloud server IPs are commonly blocked by YouTube based on ASN classification — AWS, GCP, Azure, and DigitalOcean ranges routinely trigger RequestBlocked or IpBlocked. The fix is rotating residential proxies, which route traffic through real home IP addresses that YouTube is far less likely to flag as automated. Webshare is the proxy provider integrated directly into the library via WebshareProxyConfig.

from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api.proxies import WebshareProxyConfig

proxy_config = WebshareProxyConfig(
    proxy_username="your_webshare_username",
    proxy_password="your_webshare_password",
)

ytt_api = YouTubeTranscriptApi(proxy_config=proxy_config)
transcript = ytt_api.fetch("VIDEO_ID")

The residential vs. static residential distinction matters. Webshare offers several tiers:

  • Residential (rotating): Real home IP addresses, rotated automatically. This is what works. According to Webshare's marketing, their pool contains 30M+ IPs.
  • Static Residential: Fixed residential IPs. These get flagged quickly and behave like datacenter IPs for scraping purposes.
  • Proxy Server (datacenter): IP ranges are identifiable as datacenter ASNs — YouTube blocks these just like your cloud server's IP.

You need rotating residential, not the cheaper static or datacenter tiers. This is the single most-cited mistake in community threads.

The retries_when_blocked parameter is built into WebshareProxyConfig and is the correct way to handle IP rotation on failure. When a RequestBlocked exception fires, the parameter tells the library to retry with a different IP from the pool rather than immediately raising the exception. Configure it explicitly:

proxy_config = WebshareProxyConfig(
    proxy_username="your_username",
    proxy_password="your_password",
    retries_when_blocked=3,  # retry up to 3 times with different IPs on block
)
ytt_api = YouTubeTranscriptApi(proxy_config=proxy_config)

Note: v1.2.4 fixed a bug where usernames with the -rotate suffix had the suffix appended twice — if you were on an older version and seeing auth failures, upgrading fixes this.


Retry Logic: Handling Transient Failures Without Breaking Your Pipeline

The short answer: Retrying immediately on a RequestBlocked from a flagged IP does nothing — you need IP rotation, not time delay. The retries_when_blocked parameter on WebshareProxyConfig handles this automatically. For non-IP failures (network timeouts, YouTubeDataUnparsable), a simple exponential backoff wrapper is appropriate.

For the full error taxonomy and what causes each exception, see our troubleshooting guide for the YouTube transcript API. For rate-limit specific patterns, see our rate-limit deep-dive.

Here's a production-grade fetch function that handles the main failure classes:

import time
import logging
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api import (
    TranscriptsDisabled,
    NoTranscriptFound,
    RequestBlocked,
    IpBlocked,
    VideoUnavailable,
    AgeRestricted,
    VideoUnplayable,
)
from youtube_transcript_api.proxies import WebshareProxyConfig

logger = logging.getLogger(__name__)

def fetch_transcript(
    video_id: str,
    api: YouTubeTranscriptApi,
    languages: list[str] = None,
    max_retries: int = 2,
) -> "FetchedTranscript | None":
    """
    Fetch transcript with retry logic for transient failures.
    Returns a FetchedTranscript object (call `.to_raw_data()` for list[dict]).
    Returns None for permanent failures (disabled, restricted, unavailable).
    Raises on unexpected errors.
    """
    languages = languages or ["en"]
    
    for attempt in range(max_retries + 1):
        try:
            return api.fetch(video_id, languages=languages)
        
        except (TranscriptsDisabled, AgeRestricted, VideoUnplayable):
            # Permanent failures — retrying won't help
            logger.info(f"Skipping {video_id}: permanent content restriction")
            return None
        
        except NoTranscriptFound:
            logger.info(f"No transcript in {languages} for {video_id}")
            return None
        
        except (RequestBlocked, IpBlocked):
            # WebshareProxyConfig's retries_when_blocked handles this internally
            # if proxies are configured. If you're still hitting this, your proxy
            # pool may be exhausted or proxies aren't configured.
            logger.warning(f"IP blocked fetching {video_id} (attempt {attempt + 1})")
            if attempt < max_retries:
                time.sleep(2 ** attempt)  # 1s, 2s, 4s...
            else:
                logger.error(f"IP block persists after {max_retries} retries: {video_id}")
                return None
        
        except Exception as e:
            logger.error(f"Unexpected error fetching {video_id}: {e}")
            raise
    
    return None

Batch Fetching at Scale: Threading and Async Patterns

The short answer: The library is synchronous. For processing multiple videos, use asyncio.to_thread in async contexts or a ThreadPoolExecutor for parallel fetching. Aggressive concurrency burns IP reputation faster — balance throughput against ban risk.

Async pattern (for FastAPI / async Python):

import asyncio
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api.proxies import WebshareProxyConfig

proxy_config = WebshareProxyConfig(
    proxy_username="your_username",
    proxy_password="your_password",
    retries_when_blocked=3,
)
ytt_api = YouTubeTranscriptApi(proxy_config=proxy_config)

async def fetch_transcript_async(video_id: str) -> "FetchedTranscript | None":
    return await asyncio.to_thread(ytt_api.fetch, video_id)

async def fetch_batch(video_ids: list[str], concurrency: int = 5) -> dict:
    semaphore = asyncio.Semaphore(concurrency)
    
    async def limited_fetch(vid: str):
        async with semaphore:
            result = await fetch_transcript_async(vid)
            await asyncio.sleep(1)  # 1s delay between requests — load-bearing, not cosmetic
            return vid, result
    
    results = await asyncio.gather(*[limited_fetch(v) for v in video_ids])
    return dict(results)

Threading pattern (for synchronous scripts):

from concurrent.futures import ThreadPoolExecutor, as_completed

def fetch_batch_threaded(
    video_ids: list[str],
    api: YouTubeTranscriptApi,
    max_workers: int = 5,
) -> dict:
    results = {}
    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_id = {
            executor.submit(api.fetch, vid): vid
            for vid in video_ids
        }
        for future in as_completed(future_to_id):
            vid = future_to_id[future]
            try:
                results[vid] = future.result()
            except Exception as e:
                results[vid] = None
                logger.warning(f"Failed {vid}: {e}")
    return results

Concurrency and burn rate: The concurrency: int = 5 default and the asyncio.sleep(1) delay are conservative starting points — tune based on your proxy pool size and observed 429 rate. Higher concurrency means more requests per second from your proxy pool, which means IPs get flagged faster. Watch your RequestBlocked rate — if it climbs over time, reduce concurrency or increase the delay rather than guessing.


Full Error Handling Reference

The short answer: Import all error classes explicitly from youtube_transcript_api. Each class maps to a distinct failure type with a distinct appropriate response. Don't catch the base Exception without at least logging the class name — it makes debugging nearly impossible.

The named exception classes in youtube_transcript_api as of v1.2.4:

from youtube_transcript_api import (
    TranscriptsDisabled,     # Video has captions off (or IP block misdiagnosed)
    NoTranscriptFound,       # No transcript in requested language(s)
    RequestBlocked,          # IP blocked — not a video content issue
    IpBlocked,               # Explicit IP ban
    VideoUnavailable,        # Video does not exist or is private
    AgeRestricted,           # Video requires sign-in
    VideoUnplayable,         # Region lock, embed disabled, account suspended
    InvalidVideoId,          # Malformed or non-11-char ID passed
    YouTubeDataUnparsable,   # YouTube changed internal response format
    PoTokenRequired,         # YouTube bot-detection token required (newer error class)
)

The library's base exception is CouldNotRetrieveTranscript — all of the above inherit from it. If you catch an exception that doesn't match any of the named classes above, catch CouldNotRetrieveTranscript as a fallback and log the specific class name (type(e).__name__) so you can file an accurate GitHub issue. Each unnamed exception often precedes a new named class in the next library release.


When the Library Is the Wrong Tool

The library answers the question "how do I get a transcript?" If your question is actually "how do I build a product that uses transcripts reliably without becoming the ops team for transcript infrastructure," the answer is different.

Consider what "production-ready" looks like for the DIY stack: a Webshare residential proxy subscription, active monitoring of your block rate, upgrading the library when YouTube changes its internal format, handling PoTokenRequired as YouTube's bot detection evolves, and managing concurrency thresholds empirically because YouTube doesn't publish them.

SkipTheWatch is a web app that handles all of this at the infrastructure layer — paste a YouTube URL and get an AI-generated summary, with persistent chat per video and scheduled channel monitoring. For a personal project or research pipeline, the DIY approach is fine. For a production SaaS feature, the question is whether managing transcript infrastructure is the best use of your engineering time. STW costs $9/month (500 summaries/month) after a 7-day free trial (card required, $0 during trial).

One honest limitation to flag: SkipTheWatch processes English-only — there's no multilingual support. If your pipeline needs non-English transcripts, you'll need to handle that in your own DIY stack.


FAQ

Q: Does youtube-transcript-api require an API key? A: No. It accesses the same internal timedtext endpoint that YouTube's website uses — no Google Cloud project, no quota management, no OAuth. This is the primary reason developers choose it over the official YouTube Data API v3.

Q: How do I get a transcript as plain text instead of a list of dicts? A: Use TextFormatter from youtube_transcript_api.formatters. It strips timestamps and joins segments into a clean string, which is what you want for LLM input or search indexing.

Q: Why does the library break after a YouTube update? A: The library depends on YouTube's internal timedtext API, which can change without notice. When it changes, YouTubeDataUnparsable is raised across all library versions simultaneously. Update to latest and watch the GitHub issue queue.

Q: Can I run this in an async Python app (FastAPI, etc.)? A: Yes, but the library itself is synchronous. Wrap calls with asyncio.to_thread(api.fetch, video_id) to avoid blocking the event loop.

Q: What's the retries_when_blocked parameter for? A: It's a parameter on WebshareProxyConfig that tells the library to retry with a different IP from the proxy pool when a RequestBlocked exception fires. Without it, the library raises immediately. Set it to 2–5 for production resilience.

Q: Why am I getting RequestBlocked even with proxies configured? A: Most commonly because you're using Static Residential or datacenter proxies instead of rotating residential. Webshare's "Residential" tier (not "Proxy Server" or "Static Residential") is what the library README recommends. See the troubleshooting guide for the full diagnosis flow.

Q: How many concurrent requests can I safely make? A: YouTube doesn't publish this. Community guidance is to keep concurrency at 5 or below and add 1-second delays between requests as a conservative starting point — tune based on your proxy pool size and observed block rate. Watch your RequestBlocked rate — if it climbs, reduce concurrency. These numbers are starting points, not guaranteed safe thresholds.

Q: Does this work for auto-generated captions? A: Yes. The library fetches both manually-created and auto-generated transcripts. Use .list() and check transcript.is_generated to distinguish them if needed for quality filtering.

Q: What happens if I get an exception that's not in the named error classes? A: Catch CouldNotRetrieveTranscript (the library's base exception) as a fallback, log type(e).__name__ to identify the class, and file a GitHub issue with the video ID and exception name. Unnamed exceptions often precede new named error classes in the next release.

Skip the watch. Get the insight.

AI summaries of any YouTube video in seconds — key insights, timestamps, structured breakdowns. Start free — no credit card. Pro is $9/month for 500 summaries with a 7-day free trial, cancel anytime.

Get my free summaries

Free to start · No credit card · Upgrade anytime

Related Articles