How to Get a YouTube Transcript with Python
Fetch the transcript of any YouTube video in Python: timestamps, plain text and SRT, languages, errors and batches, with requests or the official SDK.
To get a YouTube transcript with Python, send one HTTP request with the video ID to a transcript API and read the JSON that comes back: a list of segments, each with its text, start time and duration. With FetchTranscript that is GET https://api.fetchtranscript.com/v1/transcripts/{video_id} and a few lines of requests, or one call of the official SDK. This guide shows both, then covers the parts that make or break a real project: languages, auto-generated captions, errors, retries and batches of thousands of videos.
What a YouTube transcript actually is
YouTube does not store a "transcript" as such. It stores caption tracks, and a video can have several of them:
- Manual captions, uploaded or typed by the creator (or a captioning service). They are usually accurate, punctuated and properly split into sentences.
- Auto-generated captions (often called ASR, automatic speech recognition), produced by YouTube for most videos in a supported spoken language. They have no punctuation in many languages, misspell names and technical terms, and appear a while after upload.
- Translations of either kind, generated on the fly by YouTube.
A transcript is simply the text of one of those tracks, usually with timestamps. Two consequences matter for your code. First, a video may have no captions at all (the owner disabled them, or the language is not supported for automatic captions), so "no transcript" is a normal outcome, not a bug. Second, when you do not ask for a language, you need a rule for which track you get. FetchTranscript always returns the video's original language: its manual captions if there are any, otherwise the auto-generated ones, never a translation and never a track chosen by the location of the server.
Get an API key
Create a free account at the sign-up page and copy a key from the dashboard. Keys start with yt_. The free tier gives 100 calls every month; after that it is $1 per 1,000 calls, and calls that fail cost nothing (details on the pricing page). Keep the key in an environment variable rather than in your code:
export FETCHTRANSCRIPT_API_KEY="yt_your_api_key"Before writing any Python, you can check that everything works with curl:
curl -H "X-API-Key: $FETCHTRANSCRIPT_API_KEY" \
"https://api.fetchtranscript.com/v1/transcripts/dQw4w9WgXcQ?format=json"Fetch a transcript with requests
The video ID is the 11-character value after v= in a watch URL (or after youtu.be/ in a short link). Here is a complete script with nothing but requests:
import os
import requests
API = "https://api.fetchtranscript.com/v1"
HEADERS = {"X-API-Key": os.environ["FETCHTRANSCRIPT_API_KEY"]}
def get_transcript(video_id: str, lang: str | None = None) -> dict:
params = {"format": "json"}
if lang:
params["lang"] = lang
response = requests.get(f"{API}/transcripts/{video_id}", headers=HEADERS, params=params, timeout=60)
response.raise_for_status()
return response.json()
data = get_transcript("dQw4w9WgXcQ")
print(data["language"], "auto-generated" if data["is_generated"] else "manual")
for segment in data["segments"][:5]:
print(f'{segment["start"]:7.2f}s {segment["text"]}')The JSON response looks like this (shortened):
{
"video_id": "dQw4w9WgXcQ",
"language": "en",
"segments": [
{ "text": "We're no strangers to love", "start": 18.64, "duration": 3.24 }
],
"is_generated": false,
"provider": "cache",
"metadata": {
"title": "Rick Astley - Never Gonna Give You Up",
"author": "Rick Astley",
"length_seconds": 213,
"view_count": 1600000000
}
}start and duration are in seconds. is_generated tells you whether you got YouTube's automatic captions, which is worth storing: downstream code (a summarizer, a search index) may want to treat a noisy auto-generated track differently from a clean manual one. The metadata block saves you a second call when all you need is the title, the channel name and the length.
Plain text, SRT and the other formats
Segments are what you want for anything time-aware: jumping to a moment, aligning with video frames, building chapters. For reading, summarizing or feeding a language model you usually want the text alone. Ask for it with format:
format=text: the whole transcript as one plain-text string in thetextfield.format=srt: a SubRip subtitle file intext, ready to save as.srt.format=vtt: a WebVTT file intext, for HTML5 video players.format=chunks: segments merged into timestamped chunks of aboutchunk_sizecharacters (200-4000), for embeddings. The RAG guide explains how to choose the size and the overlap.
Every format costs the same single credit, so pick the one that saves you work.
params = {"format": "text", "lang": "en"}
response = requests.get(f"{API}/transcripts/dQw4w9WgXcQ", headers=HEADERS, params=params, timeout=60)
text = response.json()["text"]
print(len(text.split()), "words")If you need subtitle files rather than text, the guide to downloading YouTube subtitles as SRT or VTT goes deeper into the formats and their quirks.
The official Python SDK
If you would rather not handle URLs and status codes yourself, install the SDK:
pip install fetchtranscriptimport os
from fetchtranscript import FetchTranscriptClient
client = FetchTranscriptClient(api_key=os.environ["FETCHTRANSCRIPT_API_KEY"])
transcript = client.transcripts.get("dQw4w9WgXcQ", lang="en") # dict with segments
text = client.transcripts.get_text("dQw4w9WgXcQ") # plain text string
srt = client.transcripts.get_srt("dQw4w9WgXcQ") # SRT string
languages = client.transcripts.list_languages("dQw4w9WgXcQ")The SDK raises typed exceptions for errors and also has an async client, AsyncFetchTranscriptClient, for asyncio code. The SDK docs list every method.
Choosing a language
Pass lang with a language code such as en, es or de when you need a specific language. To see what a video offers, list its tracks first:
response = requests.get(f"{API}/transcripts/dQw4w9WgXcQ/languages", headers=HEADERS, timeout=60)
for track in response.json()["languages"]:
kind = "auto" if track["is_generated"] else "manual"
print(track["language_code"], track["language"], kind)Each entry has language_code, language (the name), is_generated and is_translatable. Keep in mind that asking for a language the video has no track in can return YouTube's automatic translation of the original track (the same translation YouTube's own player offers), with language set to the code you asked for. If you need text that was spoken or written in that language, a sensible strategy for multilingual collections is: list the tracks first and pass lang only when the language is there; otherwise call without lang to get the original language. The listing call also costs one credit, so only use it when you really need to choose between several tracks.
Handling errors properly
Errors come back as JSON with a stable code in detail.error, and none of them is billed:
{ "detail": { "error": "transcripts_disabled", "message": "Transcripts are disabled for this video", "video_id": "abc123def45" } }The ones you will meet in practice:
| HTTP | error | What to do |
|---|---|---|
| 404 | transcripts_disabled | The owner turned captions off: record it and move on |
| 404 | no_transcript_found | No track the video can serve in the requested language: retry without lang |
| 404 | video_not_found / video_unavailable | Deleted, private, age-restricted or members-only video |
| 400 | invalid_video_id | The ID is malformed: check your URL parsing |
| 429 | rate_limit_exceeded | Over 500 requests per minute: wait Retry-After seconds |
| 503 | service_unavailable | Temporary upstream problem: retry with backoff |
A wrapper that treats the "this video simply has no transcript" cases as None and retries only what is worth retrying:
import time
SKIP = {"transcripts_disabled", "no_transcript_found", "video_not_found", "video_unavailable"}
def fetch_or_none(video_id: str, lang: str | None = None, attempts: int = 4) -> dict | None:
params = {"format": "json", **({"lang": lang} if lang else {})}
for attempt in range(attempts):
r = requests.get(f"{API}/transcripts/{video_id}", headers=HEADERS, params=params, timeout=60)
if r.status_code == 200:
return r.json()
error = (r.json().get("detail") or {}).get("error") if r.headers.get("content-type", "").startswith("application/json") else None
if error in SKIP:
return None
if r.status_code in (429, 503):
time.sleep(int(r.headers.get("Retry-After", 2 ** attempt)))
continue
r.raise_for_status()
raise RuntimeError(f"gave up on {video_id}")The full list of codes is on the errors page.
Many videos at once
Transcripts are independent, so a batch is a matter of running requests concurrently while staying under the rate limit of 500 requests per minute. A thread pool of 8 to 16 workers is plenty for most jobs:
from concurrent.futures import ThreadPoolExecutor
import json
video_ids = ["dQw4w9WgXcQ", "9bZkp7q19f0", "kJQP7kiw5Fk"]
with ThreadPoolExecutor(max_workers=8) as pool:
results = dict(zip(video_ids, pool.map(fetch_or_none, video_ids)))
with open("transcripts.jsonl", "w", encoding="utf-8") as f:
for vid, data in results.items():
f.write(json.dumps({"video_id": vid, "transcript": data}, ensure_ascii=False) + "\n")
print(sum(1 for d in results.values() if d), "of", len(video_ids), "videos have a transcript")Every successful response carries an X-Credits-Remaining header (and X-Credits-Used), so a long job can log its spending as it goes and stop before the balance runs out. If the IDs come from a channel or a playlist, the channel guide and the playlist export guide show how to list them first.
Why not scrape YouTube directly?
You can. The open-source youtube-transcript-api library and yt-dlp both read captions without an API key, and for a few videos on your laptop they work well. The trouble starts on a server: YouTube blocks many requests coming from cloud providers' IP addresses, and the library then raises RequestBlocked or IpBlocked. Fixing that means buying residential proxies, rotating them and maintaining the scraper every time YouTube changes something. We compare the options honestly in youtube-transcript-api alternatives. The official YouTube Data API is not a shortcut either: it only downloads captions of videos you own, as explained in Can the YouTube Data API get transcripts?.
If you just need one transcript right now, without code, the free transcript generator does it in the browser.
Frequently asked questions
Do I need a YouTube API key to get a transcript in Python?
No. The YouTube Data API is not involved: you only need a FetchTranscript key (starting with yt_), sent in the X-API-Key header.
How do I get the video ID from a URL?
It is the v parameter of a watch URL (youtube.com/watch?v=dQw4w9WgXcQ), the path of a short link (youtu.be/dQw4w9WgXcQ) or the last part of a Shorts URL. Parse it with urllib.parse rather than string slicing, because URLs often carry extra parameters such as t= or list=.
Can I get a transcript for a video without captions?
Not from YouTube's captions: if the owner disabled them, the API answers 404 transcripts_disabled and the call is free. For such videos you would have to download the audio yourself and run a speech-to-text model.
Is the auto-generated transcript good enough?
For search, topic detection and summaries it usually is. For quotes, subtitles you publish, or names and numbers, check is_generated and prefer a manual track when the video has one.
How fast is it?
Popular videos are often already cached and answer in a fraction of a second; a cold fetch takes longer because it goes to YouTube. Plan batches around the 500 requests per minute limit rather than single-request latency.
Try it on your own videos
100 free calls every month, no credit card. Then $1 per 1,000 calls, only for the calls that succeed.
Related guides
- youtube-transcript-api Alternative: When the Library Breaks
Why the youtube-transcript-api Python library gets RequestBlocked on servers, what proxies really cost, and when a hosted transcript API is the better choice.
- YouTube Transcripts for RAG: Chunking and Embeddings
Turn YouTube videos into a searchable knowledge base: timestamped transcript chunks, chunk size and overlap, embeddings and citations to the exact second.
- How to Download YouTube Subtitles as SRT or VTT
Download the subtitles of a YouTube video as SRT, VTT or text, pick the language, tell manual captions from auto-generated ones, and batch it with code.