On this page8 sections
youtube-transcript-api is the go-to Python package for YouTube transcripts, and on your laptop it just works. Then you deploy to AWS, Render, Railway, Fly or a GitHub Actions runner and every call fails with RequestBlocked or IpBlocked. This guide covers the free route first, why it fails once deployed, and a version that behaves the same in production: a requests call, error handling by code, and a FastAPI route you can drop in.
The free route: youtube-transcript-api
pip install youtube-transcript-apifrom youtube_transcript_api import YouTubeTranscriptApi
transcript = YouTubeTranscriptApi().fetch("jNQXAC9IVRw")
print(" ".join(snippet.text for snippet in transcript.snippets))For a script on your own machine, that's the right answer and it costs nothing. Run the same code from a cloud server and you'll likely see this (we ran it from a cloud machine on 2026-11-20, library version 1.2.5):
IpBlocked:
Could not retrieve a transcript for the video https://www.youtube.com/watch?v=jNQXAC9IVRw!
This is most likely caused by:
YouTube is blocking requests from your IP. ...
- You are doing requests from an IP belonging to a cloud provider (like AWS,
Google Cloud Platform, Azure, etc.). Unfortunately, most IPs from cloud
providers are blocked by YouTube.The library is being honest: the problem is the server's network, not your code. Its README explains workarounds, which mean sourcing and paying for a different network route yourself and keeping it working. Two more things catch people in a shipped app:
- No captions, no transcript. The library reads caption tracks. Videos without one fail with
TranscriptsDisabledorNoTranscriptFound, and a speech-to-text fallback means downloading the audio and running another service. - It breaks again later. It reads YouTube's own pages and internal endpoints, so when YouTube changes them you wait for a new release.
If you only run it locally, keep the library.
The same thing with one API call
Importly takes the YouTube link and returns the transcript. It uses the video's captions when there are some, runs speech-to-text when there aren't, and works the same from a server as from your laptop:
# transcript.py
import os
import time
import requests
API = "https://api.importly.io"
HEADERS = {"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"}
class TranscriptError(Exception):
def __init__(self, code, message, status=None, retry_after=None):
super().__init__(message)
self.code = code
self.status = status
self.retry_after = retry_after
def _check(res):
body = res.json()
# The request itself was rejected: bad link, bad key, low balance, rate limit
if not res.ok:
raise TranscriptError(body.get("code"), body.get("error"), res.status_code, body.get("retryAfter"))
return body["data"]
def get_transcript(url):
data = _check(requests.post(
f"{API}/transcribe",
headers=HEADERS,
json={
"url": url,
"mode": "auto", # captions if the video has them, speech-to-text if not
"wait": True, # hold the request until the transcript is ready (up to 30s)
"maxCostDollars": 0.5, # fail instead of running over this on a long video
},
timeout=90,
))
# Still running after the wait (long video with no captions): poll every 3s
for _ in range(100):
if data["status"] == "completed":
return data["result"]
if data["status"] == "failed":
raise TranscriptError(data.get("code"), data.get("message"))
time.sleep(3)
data = _check(requests.get(f"{API}/transcribe/status", params={"id": data["jobId"]}, headers=HEADERS, timeout=30))
raise TranscriptError("TIMEOUT", f"Job {data['jobId']} still running")The result has the whole text and timestamped segments, in the same shape whether it came from captions or speech-to-text:
{
"text": "All right, so here we are, in front of the elephants\n...",
"source": "platform_captions",
"captionKind": "manual",
"language": "en",
"duration": 19,
"data": {
"segments": [
{ "start": 1.2, "end": 3.36, "text": "All right, so here we are, in front of the elephants" }
]
},
"costInDollars": 0.003
}source is platform_captions for captions and importly for speech-to-text; captionKind says whether the captions were uploaded (manual) or generated by YouTube (auto). The full field list is in the transcripts docs.
Handle errors by code
Every error has a code and a documentationUrl, so you branch on the code instead of parsing messages:
from transcript import TranscriptError, get_transcript
USER_ERRORS = {
"VIDEO_PRIVATE": "That video can't be transcribed. Is it public?",
"VIDEO_UNAVAILABLE": "That video can't be transcribed. Is it public?",
"GEO_BLOCKED": "That video isn't available.",
"LIVE_NOT_SUPPORTED": "Live streams can't be transcribed until they end.",
"INVALID_URL": "Paste a link to a single video.",
"PLAYLIST_NOT_SUPPORTED": "Paste a link to a single video.",
"MAX_COST_EXCEEDED": "That video is too long for this feature.",
}
RETRY_LATER = {"SOURCE_THROTTLED", "RATE_LIMITED"}
def transcript_text(url):
try:
return get_transcript(url)["text"]
except TranscriptError as err:
if err.code in USER_ERRORS:
raise ValueError(USER_ERRORS[err.code]) from err
if err.code in RETRY_LATER:
... # requeue; for RATE_LIMITED wait err.retry_after seconds
raise # INSUFFICIENT_BALANCE, UNAUTHORIZED, INTERNAL_ERROR: alert yourselfFailed transcriptions are refunded, so a private or removed video costs you nothing. SOURCE_THROTTLED means the source refused for a moment, and a retry usually works. The full list is on Errors & rate limits.
A FastAPI route
# main.py
from fastapi import FastAPI, HTTPException
from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel
from transcript import TranscriptError, get_transcript
app = FastAPI()
class TranscriptRequest(BaseModel):
url: str
@app.post("/api/transcript")
async def transcript(req: TranscriptRequest):
try:
result = await run_in_threadpool(get_transcript, req.url)
except TranscriptError as err:
raise HTTPException(status_code=422, detail={"code": err.code, "error": str(err)})
return {"text": result["text"], "segments": result["data"]["segments"]}get_transcript uses blocking requests, so the route runs it in a thread pool to keep the server responsive. Keep IMPORTLY_API_KEY in your host's environment variables, not in code.
Many videos, or long ones: use a webhook
For a batch, or videos long enough to need speech-to-text, send webhookUrl instead of wait. The request returns a jobId right away, and Importly posts the finished transcript (or the failure, with its code) to your endpoint. In the webhook the transcript fields sit directly on data (data.text, data.data.segments). See webhooks.
What it costs
- From captions, uploaded or auto-generated: $0.003 per video.
- Speech-to-text, when a video has no captions: $0.01 per media minute, fetching included, with a $0.01 minimum.
maxCostDollarscaps each request, and failed transcriptions are refunded.
It's free to try, no card required. See pricing.
Have your coding agent wire it in
Connect https://mcp.importly.io/mcp to Claude Code, Cursor or another coding agent and ask it to add YouTube transcripts to your Python app. It gets working code for your stack, writes the integration and tests real calls with your API key. The steps are in Have your agent build Importly into your app.
FAQ
Why does youtube-transcript-api say RequestBlocked or IpBlocked?
YouTube blocks most requests from cloud provider IPs, so the library fails on AWS, Google Cloud, Azure and similar hosts even though the same code works at home. The library's own error message says so. Send the link to an API that works from servers, like Importly, instead.
Can I get a transcript for a video with no captions?
Yes. With "mode": "auto", Importly runs speech-to-text when there are no captions, in the same request, for $0.01 per minute.
Does it work with Shorts and youtu.be links?
Yes. watch?v=, youtu.be, /shorts/ and m.youtube.com links all work as pasted. See the YouTube Shorts transcript API post.
Is there a Node.js version?
Yes: YouTube transcripts in Node.js that keep working after you deploy.
Related: Best YouTube transcript API, Video transcription API, Podcast transcription API, YouTube transcription API.