BlogImplementation Guide

Download YouTube Videos in Python Without Breaking on Your Server

pytube stopped shipping in 2023 and its fork works locally but fails on cloud servers. Download YouTube videos from Python with one requests call, error codes and a FastAPI webhook.

On this page7 sections

Most Python tutorials for downloading YouTube videos use pytube. Its last release was 15.0.0 in May 2023 (PyPI, checked 2026-11-20), and the code people copy now comes from pytubefix, the maintained fork. That works on your laptop. Deployed to AWS, Render, Railway, Fly or a CI runner, it's a different story. This guide covers the free route first, why it tends to fail once your app is deployed, and a version that behaves the same in production: a requests call, error handling by code, and a FastAPI route with a webhook.

The free route: pytubefix

pytubefix is the actively maintained fork of pytube (version 11.2.1 was published on 2026-10-16):

bash
pip install pytubefix
python
from pytubefix import YouTube

yt = YouTube("https://www.youtube.com/watch?v=jNQXAC9IVRw")
print(yt.title)

# A single file with video and audio: only offered at low resolutions
yt.streams.get_highest_resolution().download(filename="video.mp4")

For a script on your own machine, that's the right answer and it costs nothing. Three things catch people once it's part of a shipped app:

  • It breaks on the server. YouTube blocks or challenges a lot of traffic from cloud and datacenter IPs. The same code that works from home fails from Vercel, Render, Railway, Fly, AWS or a GitHub Actions runner, usually with a bot check or an error about the video being unavailable.
  • You merge the streams yourself. YouTube serves video and audio together only at low resolutions. A normal 1080p MP4 with sound means downloading the video and audio streams separately (yt.streams.filter(adaptive=True)) and running ffmpeg on your server.
  • It breaks again later. When YouTube changes how it serves video, you wait for a new release, then upgrade and redeploy while downloads are down.

If none of that applies to you (a local script, a small internal tool), keep the library.

The same thing with one API call

Importly takes the YouTube link and returns a link to the finished file, video and audio already in one MP4, at the quality you ask for. It works the same from a server as from your laptop:

python
# download.py
import os
import time

import requests

API = "https://api.importly.io"
HEADERS = {"Authorization": f"Bearer {os.environ['IMPORTLY_API_KEY']}"}


class ImportJobError(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 ImportJobError(body.get("code"), body.get("error"), res.status_code, body.get("retryAfter"))
    return body["data"]


def import_video(url, **options):
    data = _check(requests.post(
        f"{API}/import",
        headers=HEADERS,
        json={
            "url": url,
            "videoQuality": "1080p",  # a ceiling: the best stream at or below it
            "maxCostDollars": 1,  # fail instead of downloading something huge
            **options,  # e.g. includeVideo=False for audio only, webhookUrl=..., store=True
        },
        timeout=30,
    ))
    return data["jobId"]


def wait_for_import(job_id):
    for _ in range(200):
        data = _check(requests.get(f"{API}/import/status", params={"id": job_id}, headers=HEADERS, timeout=30))
        if data["status"] == "completed":
            return data["result"]  # {"mediaUrl", "title", "duration", "filename", ...}
        if data["status"] == "failed":
            raise ImportJobError(data.get("code"), data.get("message"))
        time.sleep(3)
    raise ImportJobError("TIMEOUT", f"Import {job_id} still running")

Then save the file, from a worker or a script:

python
import requests

from download import import_video, wait_for_import

job_id = import_video("https://www.youtube.com/watch?v=jNQXAC9IVRw")
result = wait_for_import(job_id)

with requests.get(result["mediaUrl"], stream=True, timeout=60) as file:
    file.raise_for_status()
    with open(result["filename"], "wb") as out:
        for chunk in file.iter_content(chunk_size=1024 * 1024):
            out.write(chunk)

mediaUrl is a signed link that lasts 7 days, so copy the file somewhere permanent. To skip that step, connect your own S3, R2 or B2 bucket once and pass store=True: the file lands in your bucket and never passes through your server. See S3 storage.

For audio only (a podcast app, or audio for your own transcription step), pass includeVideo=False. It costs much less because only the audio is downloaded.

Handle errors by code

Failed jobs and rejected requests both carry a code, so you branch on the code instead of parsing messages:

python
from download import ImportJobError, import_video, wait_for_import

USER_ERRORS = {
    "VIDEO_PRIVATE": "That video can't be downloaded. Is it public?",
    "VIDEO_UNAVAILABLE": "That video can't be downloaded. Is it public?",
    "GEO_BLOCKED": "That video isn't available.",
    "LIVE_NOT_SUPPORTED": "Live streams can be downloaded once 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. Try a lower quality.",
    "FILE_TOO_LARGE": "That video is too long. Try a lower quality.",
}
RETRY_LATER = {"SOURCE_THROTTLED", "RATE_LIMITED"}


def download(url):
    try:
        return wait_for_import(import_video(url))
    except ImportJobError 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 yourself

Failed imports aren't charged (except FILE_TOO_LARGE, which pays for what was downloaded before your balance ran out). SOURCE_THROTTLED means the source refused for a moment, and a retry a little later usually works. The full list is on Errors & rate limits.

A FastAPI route with a webhook

Downloads can take longer than a web request should wait, so in an app, start the job in one route and receive the result in another:

python
# main.py
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel

from download import ImportJobError, import_video, wait_for_import

app = FastAPI()


class ImportRequest(BaseModel):
    url: str


@app.post("/api/import")
async def start_import(req: ImportRequest):
    try:
        job_id = await run_in_threadpool(
            import_video, req.url, webhookUrl="https://example.com/api/import/webhook"
        )
    except ImportJobError as err:
        raise HTTPException(status_code=422, detail={"code": err.code, "error": str(err)})
    # save job_id against the user's record here
    return {"jobId": job_id}


@app.post("/api/import/webhook")
async def import_webhook(request: Request):
    job_id = (await request.json())["data"]["jobId"]
    # Confirm with the API instead of trusting the payload: returns the result or raises the failure
    try:
        result = await run_in_threadpool(wait_for_import, job_id)
        # update the record for job_id with result["mediaUrl"]
    except ImportJobError as err:
        ...  # show err.code to the user
    return Response(status_code=204)

import_video and wait_for_import use blocking requests, so the routes run them in a thread pool to keep the server responsive. The webhook sends one POST when the job finishes, with success: false and the code if it failed. Deliveries aren't retried, so poll jobs you haven't heard back about as a fallback. See webhooks. Keep IMPORTLY_API_KEY in your host's environment variables, not in code.

What it costs

  • Downloads are $0.002 per MB downloaded, with a $0.01 minimum per import. A 3-minute video at 720p is about $0.08; a 10-minute one about $0.15.
  • maxCostDollars caps each import, includeVideo=False gets audio only for much less, and failed imports are free.

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 downloads 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

Is pytube still maintained?

The original pytube package's last release was 15.0.0 in May 2023. pytubefix is the maintained fork and still ships updates.

Why does my YouTube download work locally but fail on my server?

YouTube blocks or challenges a lot of traffic from cloud and datacenter IPs, so code that works from a home connection fails from AWS, Render, Railway or a CI runner. It's the server's network, not your code.

How do I get 1080p with audio in Python?

With a library, download the video and audio streams separately and merge them with ffmpeg. With Importly, send "videoQuality": "1080p" and you get one MP4 with both.

Can I get the transcript too?

Yes. Add "includeTranscript": True to the import and the result includes a timestamped transcript. For transcripts alone, see YouTube transcripts in Python.

Related: YouTube downloader API, Download YouTube videos in Node.js, Upload a video from a URL to S3, YouTube transcripts in Python.

Keep reading

Put video and audio links to work in your app

One API for files, transcripts and metadata. Free to try, no card required.

Try free →