YouTube Transcript API in Python
This page shows how to get a YouTube transcript in Python with TranscriptAPI. You send one HTTPS request with a video URL or ID and get back the transcript as JSON segments or plain text. The only library you need is requests.
Prefer another language? See the JavaScript / Node.js and cURL quick starts.
Before you start
Section titled “Before you start”-
An API key. Sign up to get 100 free credits (no card required), then copy a key from the API Keys dashboard.
-
Python 3 with
requests:Terminal window pip install requests -
Your key in an environment variable, so it never ends up in your code:
Terminal window export TRANSCRIPT_API_KEY="your_api_key"
Each successful transcript request costs 1 credit. Failed requests (4xx and 5xx) cost nothing. See Credit Usage & Billing.
Get a transcript
Section titled “Get a transcript”Save this as transcript.py and run python transcript.py:
import osimport requests
API_KEY = os.environ["TRANSCRIPT_API_KEY"]
response = requests.get( "https://transcriptapi.com/api/v2/youtube/transcript", params={"video_url": "https://www.youtube.com/watch?v=dQw4w9WgXcQ"}, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=60,)response.raise_for_status()data = response.json()
print(data["video_id"], data["language"], data["lengthText"])for segment in data["transcript"][:3]: print(f"[{segment['start']}s] {segment['text']}")video_url accepts a full URL (https://www.youtube.com/watch?v=...), a short URL (https://youtu.be/...), or the 11-character video ID.
Response (shortened):
{ "video_id": "dQw4w9WgXcQ", "language": "en", "transcript": [ { "text": "[♪♪♪]", "start": 1.36, "duration": 1.68 }, { "text": "♪ We're no strangers to love ♪", "start": 18.64, "duration": 3.24 }, { "text": "♪ You know the rules\nand so do I ♪", "start": 22.64, "duration": 4.32 } ], "length_seconds": 213, "lengthText": "3:33"}Each segment has the caption text, its start time in seconds, and its duration in seconds. The full field list is in the API Reference.
Check a video first (free)
Section titled “Check a video first (free)”Not every video has a transcript. Before you spend a credit, ask GET /youtube/info. It takes the same video_url as the transcript endpoint. The API Reference says “no credit is consumed” and “The same API key and active plan are required as for the transcript endpoint.”
A 200 gives you the video’s metadata (title, author_name, author_url, thumbnail_url) and available_languages, a list of code, name, and kind entries. A 404 means the video does not exist or has no captions, so there is nothing to fetch.
import osimport requests
API_KEY = os.environ["TRANSCRIPT_API_KEY"]BASE_URL = "https://transcriptapi.com/api/v2"HEADERS = {"Authorization": f"Bearer {API_KEY}"}VIDEO = "dQw4w9WgXcQ"
# No credits: does the video exist, and does it have captions?info = requests.get( f"{BASE_URL}/youtube/info", params={"video_url": VIDEO}, headers=HEADERS, timeout=60,)if info.status_code == 404: print("No transcript for this video:", info.json()["detail"])else: info.raise_for_status() details = info.json() print(details["metadata"]["title"], "by", details["metadata"]["author_name"]) print("Languages:", [lang["code"] for lang in details["available_languages"]])
# 1 credit: now fetch the transcript response = requests.get( f"{BASE_URL}/youtube/transcript", params={"video_url": VIDEO}, headers=HEADERS, timeout=60, ) response.raise_for_status() print(len(response.json()["transcript"]), "segments")This check is most useful in batch jobs, where some videos in a list have no captions.
Get plain text and save it to a file
Section titled “Get plain text and save it to a file”Set format to text and include_timestamp to false to get the whole transcript as one string. That’s useful for LLM prompts, search indexes, or notes. Add send_metadata to get the video title and channel as well.
import osimport requests
API_KEY = os.environ["TRANSCRIPT_API_KEY"]
response = requests.get( "https://transcriptapi.com/api/v2/youtube/transcript", params={ "video_url": "dQw4w9WgXcQ", "format": "text", "include_timestamp": "false", "send_metadata": "true", }, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=60,)response.raise_for_status()data = response.json()
with open(f"{data['video_id']}.txt", "w", encoding="utf-8") as f: f.write(data["transcript"])
print("Saved transcript of:", data["metadata"]["title"])With include_timestamp left at true, text output keeps one line per segment in the form [18.64s] text.
Choose a transcript language
Section titled “Choose a transcript language”/youtube/info costs no credits and lists the languages a video offers. Pass a comma-separated priority list in language and the API returns the first one that exists. The language field in the response tells you which one you got. Codes starting with asr are YouTube’s auto-generated captions.
import osimport requests
API_KEY = os.environ["TRANSCRIPT_API_KEY"]BASE_URL = "https://transcriptapi.com/api/v2"HEADERS = {"Authorization": f"Bearer {API_KEY}"}
# No credits: list the transcript languages a video offersinfo = requests.get( f"{BASE_URL}/youtube/info", params={"video_url": "dQw4w9WgXcQ"}, headers=HEADERS, timeout=60,).json()print([lang["code"] for lang in info["available_languages"]])
# 1 credit: German if available, otherwise Englishdata = requests.get( f"{BASE_URL}/youtube/transcript", params={"video_url": "dQw4w9WgXcQ", "language": "de,en"}, headers=HEADERS, timeout=60,).json()print("Got:", data["language"])If none of the requested languages exist, the API returns a 404 that lists the languages the video does have. See language for the full rules.
Errors you might see
Section titled “Errors you might see”Failed requests cost no credits. Every error response has a detail field. These are the ones you are most likely to meet.
401 Unauthorized. The API key is missing or wrong. The response has a WWW-Authenticate: Bearer header and a short message:
{ "detail": "Invalid API key" }Check that TRANSCRIPT_API_KEY is set in the shell that runs your script, and that the key still exists in the API Keys dashboard. Don’t retry until you fix the key.
402 Payment Required. You have run out of credits, or you have no active plan. Here detail is an object with a reason and a link to fix it:
{ "detail": { "message": "You have an active plan, but you've run out of credits.", "reason": "insufficient_credits", "action_label": "Top up credits", "action_url": "https://transcriptapi.com/top-up" }}When reason is no_active_paid_plan, action_url points to Billing instead. Free endpoints such as /youtube/info also need an active plan, so they can return 402 too. Open action_url, then send the request again.
404 Not Found. There is no transcript to return. The code field tells you why:
{ "detail": "No transcript available for video tfLTHCpPsSY", "code": "no_captions"}Other codes are video_unavailable, age_restricted, live_not_started, and no_transcript_for_requested_languages. The last one comes with an available_languages list you can retry with. Branch on code, not on detail. Don’t retry the same request, except live_not_started after the stream has aired. Each code is explained in 404 error codes.
429 Too Many Requests. You went over your plan’s rate limit, which all API keys on your account share. Wait the number of seconds in the Retry-After header, then retry. Rate-limited requests cost no credits.
You might also see 422 when video_url is not a valid URL or video ID (fix the input), or 408 and 503 for a temporary failure (retry after a few seconds).
Handle errors and retries
Section titled “Handle errors and retries”Retry 408, 429, and 503, and wait for the Retry-After header when the API sends one. Don’t retry the other errors, because the request itself needs fixing.
import osimport timeimport requests
API_KEY = os.environ["TRANSCRIPT_API_KEY"]RETRYABLE = {408, 429, 503}
def get_transcript(video_url, max_retries=3, **params): for attempt in range(max_retries): response = requests.get( "https://transcriptapi.com/api/v2/youtube/transcript", params={"video_url": video_url, **params}, headers={"Authorization": f"Bearer {API_KEY}"}, timeout=60, ) if response.status_code == 200: return response.json() if response.status_code in RETRYABLE and attempt < max_retries - 1: # Use Retry-After when the API sends it, otherwise back off 1s, 2s, 4s... time.sleep(int(response.headers.get("Retry-After", 2 ** attempt))) continue # 401 bad key, 402 no credits, 404 no transcript, 422 invalid URL: don't retry raise RuntimeError(f"{response.status_code}: {response.json().get('detail')}")
print(get_transcript("dQw4w9WgXcQ")["lengthText"])The full error list and response bodies are in Error Handling.
Get transcripts for a channel’s latest videos
Section titled “Get transcripts for a channel’s latest videos”/youtube/channel/latest costs no credits and returns a channel’s 15 most recent uploads. It accepts an @handle, a channel URL, or a UC... ID. Each transcript you then fetch costs 1 credit.
import osimport requests
API_KEY = os.environ["TRANSCRIPT_API_KEY"]BASE_URL = "https://transcriptapi.com/api/v2"HEADERS = {"Authorization": f"Bearer {API_KEY}"}
# No credits: the channel's 15 most recent uploads (RSS)latest = requests.get( f"{BASE_URL}/youtube/channel/latest", params={"channel": "@TED"}, headers=HEADERS, timeout=60,).json()
# 1 credit per transcriptfor video in latest["results"][:3]: response = requests.get( f"{BASE_URL}/youtube/transcript", params={"video_url": video["videoId"], "format": "text", "include_timestamp": "false"}, headers=HEADERS, timeout=60, ) if response.status_code == 200: print(video["title"], "->", len(response.json()["transcript"].split()), "words") else: print(video["title"], "-> no transcript", response.status_code)The same key also works for search, paginated channel videos, and playlists.
Using the youtube-transcript-api package?
Section titled “Using the youtube-transcript-api package?”youtube-transcript-api is a free, open-source Python library that reads YouTube’s caption tracks from your own machine or server. TranscriptAPI is a hosted REST API, so your code sends one HTTPS request and the request to YouTube runs on our side. If you are moving code over from the library, the migration guide shows before-and-after code for each change.
Next steps
Section titled “Next steps”- API Reference: every endpoint, parameter, and response field
- MCP server: use the same account from Claude, ChatGPT, and other AI assistants
- Python tutorial on the blog: async batch processing with
aiohttp - Swagger UI: try requests in your browser