How to Build a YouTube Summarizer API in Python (Transcripts + LLM, Step by Step)
You want to summarize YouTube videos programmatically — pull the transcript, feed it to an LLM, get clean output. No magic required: two libraries, ~50 lines of Python, and you have a working YouTube summarizer pipeline. This guide walks through every step, including chunking long videos, estimating costs, and handling rate limits.
What Does a YouTube Summarizer API Actually Need?
Short answer: Two things — a transcript fetcher (youtube-transcript-api) and an LLM API call (OpenAI or Anthropic). That's the whole pipeline.
There is no official YouTube API endpoint that returns a transcript or summary. YouTube's Data API v3 gives you metadata — title, description, view count — but not captions unless they were manually uploaded in a specific format. The approach that actually works in production is:
- Pull the auto-generated or manually uploaded transcript using
youtube-transcript-api - Send that transcript text to an LLM with a prompt asking for a summary
- Return the result to your application
Both steps are reliable, well-documented, and cheap to run. Let's build it.
Step 1: Fetch the YouTube Transcript
Short answer: Install youtube-transcript-api, instantiate the class, call .fetch(), then access .text on each snippet.
Install the library:
pip install youtube-transcript-api
As of v1.x, the API is instance-based — you create a YouTubeTranscriptApi object and call .fetch() on it:
from youtube_transcript_api import YouTubeTranscriptApi
def get_transcript(video_id: str) -> str:
api = YouTubeTranscriptApi()
transcript_list = api.fetch(video_id)
# Each snippet has .text, .start, and .duration attributes
full_text = " ".join(snippet.text for snippet in transcript_list)
return full_text
The video_id is the v= parameter in any YouTube URL. For https://www.youtube.com/watch?v=dQw4w9WgXcQ, the ID is dQw4w9WgXcQ.
A few things to know about transcript availability:
- Auto-generated captions exist for most English-language videos. Non-English videos may have them too, but quality varies.
- Some creators disable captions entirely. In that case
youtube-transcript-apiraises aTranscriptsDisabledexception — catch it and handle gracefully. - Live streams and very new videos may not have transcripts yet.
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
def get_transcript_safe(video_id: str) -> str | None:
try:
api = YouTubeTranscriptApi()
transcript_list = api.fetch(video_id)
return " ".join(snippet.text for snippet in transcript_list)
except TranscriptsDisabled:
print(f"Transcripts are disabled for video {video_id}")
return None
except NoTranscriptFound:
print(f"No transcript found for video {video_id}")
return None
For a deeper look at edge cases and language selection, see our YouTube Transcript API guide.
Step 2: Summarize With an LLM API
Short answer: Pass the transcript text to OpenAI's Chat Completions endpoint (or Anthropic's Messages API) with a concise system prompt. Both work well; pick whichever you already have a key for.
Option A — OpenAI
pip install openai
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from environment
def summarize_with_openai(transcript: str) -> str:
response = client.chat.completions.create(
model="gpt-4o-mini", # cheap and fast; swap to gpt-4o for higher quality
messages=[
{
"role": "system",
"content": (
"You are a concise summarizer. Given a YouTube video transcript, "
"return a summary with: (1) a one-paragraph overview, "
"(2) 3-5 key takeaways as bullet points."
),
},
{"role": "user", "content": transcript},
],
max_tokens=600,
)
return response.choices[0].message.content
Option B — Anthropic (Claude)
pip install anthropic
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from environment
def summarize_with_claude(transcript: str) -> str:
message = client.messages.create(
model="claude-haiku-4-5", # fast and inexpensive; swap to claude-sonnet-4-6 for richer output
max_tokens=600,
messages=[
{
"role": "user",
"content": (
"Summarize this YouTube transcript. Return a one-paragraph overview "
"followed by 3-5 bullet-point key takeaways.\n\n"
f"Transcript:\n{transcript}"
),
}
],
)
return message.content[0].text
Both approaches produce nearly identical results for straightforward summarization. gpt-4o-mini and claude-haiku-4-5 are the cost-efficient picks for high-volume pipelines.
Step 3: Handle Long Videos With Chunking
Short answer: Split the transcript into overlapping chunks of ~3,000 words each, summarize every chunk individually, then do a second LLM call to merge the chunk summaries into one final summary.
Most LLMs accept context windows of 100k+ tokens, but you should still chunk for two practical reasons: cost (sending 40k tokens per request adds up) and quality (LLMs sometimes lose coherence on very long inputs).
A 1-hour YouTube video produces roughly 8,000–12,000 words of transcript. Here is a chunk-and-merge implementation:
def chunk_text(text: str, chunk_size: int = 3000, overlap: int = 200) -> list[str]:
"""Split text into overlapping word-count chunks."""
words = text.split()
chunks = []
start = 0
while start < len(words):
end = start + chunk_size
chunks.append(" ".join(words[start:end]))
start += chunk_size - overlap
return chunks
def summarize_long_transcript(transcript: str) -> str:
chunks = chunk_text(transcript)
if len(chunks) == 1:
return summarize_with_openai(transcript)
# Summarize each chunk
chunk_summaries = []
for i, chunk in enumerate(chunks):
print(f"Summarizing chunk {i + 1}/{len(chunks)}...")
summary = summarize_with_openai(chunk)
chunk_summaries.append(summary)
# Merge chunk summaries into a final summary
combined = "\n\n".join(chunk_summaries)
merge_prompt = (
"Below are partial summaries of different sections of a YouTube video. "
"Combine them into a single coherent summary: one overview paragraph and "
"5-7 bullet-point key takeaways.\n\n" + combined
)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": merge_prompt}],
max_tokens=800,
)
return response.choices[0].message.content
The overlap=200 words ensures context doesn't get cut mid-sentence at chunk boundaries.
Step 4: Putting the Full Pipeline Together
Short answer: Combine transcript fetch + chunked summarizer into one function, add basic retry logic, and you have a production-ready summarizer.
import time
from youtube_transcript_api import YouTubeTranscriptApi, TranscriptsDisabled, NoTranscriptFound
from openai import OpenAI, RateLimitError
client = OpenAI()
def summarize_youtube_video(video_id: str, retries: int = 3) -> dict:
# 1. Fetch transcript
try:
api = YouTubeTranscriptApi()
transcript_list = api.fetch(video_id)
transcript = " ".join(snippet.text for snippet in transcript_list)
except (TranscriptsDisabled, NoTranscriptFound) as e:
return {"error": str(e), "video_id": video_id}
# 2. Summarize with retry on rate limit
for attempt in range(retries):
try:
summary = summarize_long_transcript(transcript)
return {"video_id": video_id, "summary": summary, "word_count": len(transcript.split())}
except RateLimitError:
wait = 2 ** attempt # exponential backoff: 1s, 2s, 4s
print(f"Rate limited. Waiting {wait}s before retry {attempt + 1}/{retries}...")
time.sleep(wait)
return {"error": "Rate limit retries exhausted", "video_id": video_id}
# Usage
result = summarize_youtube_video("dQw4w9WgXcQ")
print(result["summary"])
For more detail on extracting transcripts reliably, see how to extract a YouTube transcript and our guide on generating a transcript and summary together.
Cost and Rate-Limit Estimates
Short answer: A typical 20-minute video costs under $0.01 to summarize with gpt-4o-mini or claude-haiku. Rate limits matter only above ~100 requests/minute.
Rough numbers for a 20-minute video (~3,500 words of transcript, ~4,700 tokens):
| Model | Input cost | Output cost | Approximate total |
|---|---|---|---|
| gpt-4o-mini | $0.00015/1K tokens | $0.0006/1K tokens | ~$0.001 |
| claude-haiku-4-5 | $0.00025/1K tokens | $0.00125/1K tokens | ~$0.002 |
| gpt-4o | $0.0025/1K tokens | $0.01/1K tokens | ~$0.016 |
At 1,000 summaries/month, you are looking at $1–$2 for the LLM API. The transcript fetch is free. This is genuinely cheap to run.
Rate limits: OpenAI's Tier 1 defaults allow 500 requests per minute for gpt-4o-mini. Anthropic's defaults are similar. Exponential backoff (as shown above) handles transient 429s cleanly. If you are processing a backlog of hundreds of videos in parallel, add a semaphore to limit concurrency:
import asyncio
semaphore = asyncio.Semaphore(10) # max 10 concurrent requests
async def summarize_with_limit(video_id: str):
async with semaphore:
return summarize_youtube_video(video_id)
What If You Don't Want to Build and Maintain This?
Short answer: SkipTheWatch is a no-code web app — not an API or SDK — that handles summarization for you in a browser, with no code required.
Building your own pipeline is the right call if you need programmatic access, want to integrate summaries into your own product, or are processing videos in bulk. This guide gives you everything you need for that.
But if your use case is simpler — you want to quickly read what a YouTube video is about without watching it, and you do not need API access — then standing up a Python service is overkill.
SkipTheWatch is a web app built for that scenario. Paste a YouTube URL, get a summary. No code, no API keys to manage, no infrastructure to maintain. It is aimed at readers and researchers, not developers building pipelines. To be explicit: SkipTheWatch does not offer a public API, webhook, or SDK — it is a consumer web application.
Pricing is $9/month after a 7-day free trial. A card is required at sign-up; cancel anytime in the trial for $0. The plan includes 500 summaries per month.
If you are a developer who wants a quick summary for your own reading rather than a production pipeline, it is a reasonable alternative to spinning up your own infrastructure.
Frequently Asked Questions
Is there an official YouTube API for summaries?
No. YouTube's Data API v3 does not return transcripts or summaries. You need a third-party library like youtube-transcript-api to fetch captions, then a separate LLM call to generate the summary. There is no single endpoint that does both.
What is the correct syntax for youtube-transcript-api v1.x?
In v1.x you instantiate the class and call .fetch() on the instance: api = YouTubeTranscriptApi(); snippets = api.fetch(video_id). Each snippet exposes .text, .start, and .duration as attributes. The older class-method syntax from pre-1.0 (YouTubeTranscriptApi.get_transcript()) is deprecated and will raise errors in current versions.
How do I handle videos where transcripts are disabled?
Catch TranscriptsDisabled and NoTranscriptFound from the youtube_transcript_api module. If you need captions for videos without them, the only option is audio-based transcription — download the audio with yt-dlp --extract-audio --audio-format mp3 and run it through Whisper or a speech-to-text API, which adds latency and cost.
Which LLM gives the best summaries?
For most videos, gpt-4o-mini and claude-haiku-4-5 produce good summaries at minimal cost and are the right default. For technical, dense, or academic content where accuracy matters more than speed, gpt-4o or claude-sonnet-4-6 improve coherence noticeably. Run both on a sample of your target videos and compare before committing.
Can I run this serverlessly (Lambda, Cloud Functions)?
Yes. Both youtube-transcript-api and the OpenAI/Anthropic SDKs install cleanly as Lambda layers or in a container image. The main constraint is execution timeout — a long video with chunked summarization may take 15–30 seconds. AWS Lambda's max is 15 minutes, so that is not a practical ceiling. Cold start on a Python Lambda with these dependencies is roughly 1–2 seconds with a container image deployment.