Skip to content
EN
Get API key
Browse documentation

Guides

yt-dlp Python API

Runnable Python examples for downloads, metadata, AI datasets and resumable workers.

On this page

Install the Python library

In your Python 3.11+ environment
python -m pip install -U --pre "yt-dlp[default,curl-cffi]"

Also install Deno, FFmpeg and ffprobe. These examples run locally on Linux, macOS or Windows and need no API key. Keep the executables on the worker’s PATH.

Download your first video

Download one video
from yt_dlp import YoutubeDL
from yt_dlp.networking.impersonate import ImpersonateTarget

options = {
    "js_runtimes": {"deno": {}},
    "impersonate": ImpersonateTarget(),
    "concurrent_fragment_downloads": 1,
    "noplaylist": True,
    "outtmpl": "downloads/%(id)s.%(ext)s",
    "format": "bv*[height<=1080]+ba/b[height<=1080]",
}
with YoutubeDL(options) as downloader:
    downloader.download(["https://www.youtube.com/watch?v=jNQXAC9IVRw"])
This writes local media up to 1080p and can merge separate streams. The output container depends on the selected source formats.

CLI settings are not inherited. Set Deno, impersonation and pacing in the Python options, even when your terminal command already uses them.

download() takes a list of URLs and returns a status code. extract_info(url, download=True) returns extraction information as well as performing the download. Use a context manager to close the instance cleanly, and create a fresh instance for an independent job rather than sharing mutable state across threads.

Read metadata without media

Export a small metadata record
import json
from yt_dlp import YoutubeDL
from yt_dlp.networking.impersonate import ImpersonateTarget

url = "https://www.youtube.com/watch?v=jNQXAC9IVRw"
options = {
    "js_runtimes": {"deno": {}},
    "impersonate": ImpersonateTarget(),
    "noplaylist": True,
    "sleep_interval_requests": 3,
}
with YoutubeDL(options) as downloader:
    info = downloader.sanitize_info(downloader.extract_info(url, download=False))

record = {key: info.get(key) for key in (
    "id", "webpage_url", "title", "channel_id", "duration", "upload_date"
)}
print(json.dumps(record, ensure_ascii=False, indent=2))
download=False still performs network requests. sanitize_info makes the result JSON-compatible; it does not redact secrets or reduce the result to these fields.

Extracted fields can be absent or null. Use get() for optional metadata, and do not assume every source has a duration, channel ID or complete format list. A flat playlist listing is also different from a fully resolved video. For a public response, project only the fields you intend to expose.

Avoid a metadata extraction immediately followed by an identical download extraction for every source unless your application needs the extra planning step. It duplicates source requests. If you need a durable job, store the source ID and output policy; a signed media URL from the metadata is not a durable replacement for the original source.

Python option reference

TaskPython optionDetail
Output directory and filename"outtmpl": "downloads/%(id)s.%(ext)s"Keep the source ID and dynamic extension.
Hard 1080p ceiling"format": "bv*[height<=1080]+ba/b[height<=1080]"Allows source codecs and fails if none match the bound.
Metadata sidecar"writeinfojson": TrueKeeps full extraction metadata beside the media.
Completed-ID checkpoint"download_archive": "archive.txt"One archive per output policy; not a checksum inventory.
Strict errors"ignoreerrors": FalseLets the caller record failures instead of treating post-processing problems as success.
Deno runtime"js_runtimes": {"deno": {}}Install Deno in the worker and make its binary visible on PATH.
Browser impersonation"impersonate": ImpersonateTarget()Python equivalent of --impersonate=""; import the target class and install curl-cffi.
Existing cookie file"cookiefile": "private/youtube-cookies.txt"Use private session credentials only when needed for access.
MP3 conversion options
audio_options = {
    "format": "ba",
    "outtmpl": "audio/%(id)s.%(ext)s",
    "postprocessors": [{
        "key": "FFmpegExtractAudio",
        "preferredcodec": "mp3",
        "preferredquality": "192",
    }],
}
Pass audio_options to YoutubeDL. The FFmpeg post-processor converts to a target bitrate of 192 kbps; it does not improve the source's original quality.

Video + audio + captions for an AI dataset

Use this output policy when the goal is a training dataset rather than the worker example's 1080p collection. It requests bestvideo and bestaudio, lets FFmpeg merge them into MP4, and saves available English captions and metadata beside the media.

One dataset item in Python
from yt_dlp import YoutubeDL
from yt_dlp.networking.impersonate import ImpersonateTarget

url = "https://www.youtube.com/watch?v=jNQXAC9IVRw"
options = {
    "js_runtimes": {"deno": {}},
    "impersonate": ImpersonateTarget(),
    "noplaylist": True,
    "format": "bestvideo+bestaudio/best",
    "merge_output_format": "mp4",
    "postprocessors": [{
        "key": "FFmpegVideoRemuxer",
        "preferedformat": "mp4",
    }],
    "outtmpl": "dataset/%(id)s/%(id)s.%(ext)s",
    "writeinfojson": True,
    "writesubtitles": True,
    "writeautomaticsub": True,
    "subtitleslangs": ["en"],
    "subtitlesformat": "vtt/best",
    "sleep_interval_requests": 2,
    "sleep_interval_subtitles": 5,
    "sleep_interval": 5,
    "max_sleep_interval": 10,
    "concurrent_fragment_downloads": 1,
    "retries": 3,
    "fragment_retries": 3,
}
with YoutubeDL(options) as downloader:
    downloader.download([url])
Requires FFmpeg/ffprobe, Deno and the nightly [default,curl-cffi] installation. The remuxer's preferedformat parameter is spelled that way in yt-dlp's API.

ImpersonateTarget() selects any available browser target, matching --impersonate="". Pass the object, not an empty string copied from CLI syntax. curl-cffi must be installed in this Python environment. Deno still performs JavaScript solving; impersonation does not replace it.

MP4 is the output container; the selected video can still be AV1 or VP9. If your training decoder requires H.264/AAC, apply an explicit codec policy before merging or record a separate FFmpeg transcode. Available subtitles are retrieved, not generated from speech.

After the media finishesWhat the dataset record needs
Check the final MP4 with ffprobeVideo/audio codecs, duration, dimensions, file path and byte count.
Check caption sidecars separatelyLanguage, supplied/automatic track, timestamps and whether the file actually exists.
No matching captions availableKeep the media and mark text missing; send audio to your transcription stage if required.
Captions hit 429Retry caption retrieval after an IP cooldown with subtitle pacing; do not redownload the completed media.

For a batch, use a separate archive for this dataset policy and keep an inventory for required sidecars. Do not reuse an earlier 1080p or media-only archive: it may skip videos before their newly required captions are collected. Use after_move for media readiness, then validate text and metadata before publishing a complete dataset item.

Know when the final file is ready

A progress hook reporting status=finished means a transfer finished. FFmpeg may still need to merge video and audio, convert an audio file, or move the output. A video-only stream reaching 100% is not the completion event your application should publish.

StageWhat you knowApplication state
DownloadingSome media bytes are arriving.running
Transfer hook: finishedThis transfer ended; processing can still follow.processing
after_move post-processorThe file has passed the configured post-processing and final move.local file ready
Upload and integrity checkYour destination has the object and recorded verification.delivered

The complete example below registers a custom PostProcessor at after_move and reads info["filepath"] there. It checks that the file exists and is nonempty. This avoids guessing the final extension with prepare_filename(), which can refer to a pre-conversion name.

Complete script: single-video worker

Save this as download_video.py. It accepts a video ID or watch/Shorts/live/embed URL and rejects playlist/channel input. Each invocation uses one YoutubeDL instance, bounded downloader retries and a collection-local archive. A repeated completed source returns skipped instead of pretending a new file was created.

download_video.py
import argparse
import json
import re
from pathlib import Path
from urllib.parse import parse_qs, urlparse

from yt_dlp import YoutubeDL
from yt_dlp.networking.impersonate import ImpersonateTarget
from yt_dlp.postprocessor.common import PostProcessor
from yt_dlp.utils import DownloadError, PostProcessingError


def watch_url(value):
    """Accept a video ID or a single YouTube video URL, never a playlist."""
    video_id = value
    if not re.fullmatch(r"[A-Za-z0-9_-]{11}", value):
        parsed = urlparse(value)
        parts = parsed.path.strip("/").split("/")
        host = (parsed.hostname or "").lower()
        if parsed.scheme not in {"http", "https"}:
            raise ValueError("Use a YouTube watch URL or 11-character video ID")
        if host in {"youtu.be", "www.youtu.be"}:
            video_id = parts[0]
        elif host in {"youtube.com", "www.youtube.com", "m.youtube.com"}:
            if parsed.path == "/watch":
                video_id = parse_qs(parsed.query).get("v", [""])[0]
            elif len(parts) == 2 and parts[0] in {"shorts", "live", "embed"}:
                video_id = parts[1]
            else:
                video_id = ""
        else:
            video_id = ""
    if not re.fullmatch(r"[A-Za-z0-9_-]{11}", video_id):
        raise ValueError("Expected one YouTube video, not a channel or playlist")
    return "https://www.youtube.com/watch?v=" + video_id


class FinalFile(PostProcessor):
    def __init__(self):
        super().__init__()
        self.result = None

    def run(self, info):
        path = Path(info["filepath"]).resolve()
        if not path.is_file() or path.stat().st_size == 0:
            raise PostProcessingError("Final media file is missing or empty")
        self.result = {
            "status": "completed", "video_id": info["id"],
            "title": info.get("title"), "duration": info.get("duration"),
            "path": str(path), "bytes": path.stat().st_size,
        }
        return [], info


def download_video(source, output="downloads"):
    url = watch_url(source)
    folder = Path(output).resolve()
    folder.mkdir(parents=True, exist_ok=True)
    final_file = FinalFile()
    options = {
        "js_runtimes": {"deno": {}},
        "impersonate": ImpersonateTarget(),
        "concurrent_fragment_downloads": 1,
        "noplaylist": True,
        "format": "bv*[height<=1080]+ba/b[height<=1080]",
        "outtmpl": str(folder / "%(id)s.%(ext)s"),
        "download_archive": str(folder / "archive.txt"),
        "writeinfojson": True,
        "ignoreerrors": False,
        "retries": 3, "fragment_retries": 3, "socket_timeout": 30,
        "sleep_interval_requests": 1,
        "sleep_interval": 5, "max_sleep_interval": 10,
    }
    with YoutubeDL(options) as downloader:
        downloader.add_post_processor(final_file, when="after_move")
        downloader.extract_info(url, download=True)
    if final_file.result is None:
        return {"status": "skipped", "source": url,
                "reason": "No new file recorded; check the archive"}
    return {**final_file.result, "source": url}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("source", help="YouTube video URL or ID")
    parser.add_argument("--output", default="downloads")
    args = parser.parse_args()
    try:
        result = download_video(args.source, args.output)
    except (DownloadError, ValueError, OSError) as error:
        raise SystemExit(f"Job failed: {error}") from error
    print(json.dumps(result, ensure_ascii=False, indent=2))
The full script is also available from the download link above. It owns local output only; add decoding checks and upload records at the next stage of your application.
Run one job
python download_video.py "https://www.youtube.com/watch?v=jNQXAC9IVRw" --output downloads

The completed record contains the canonical source URL, video ID, final path and byte size. A skipped record means no new final-file callback ran; reconcile it against the archive and existing inventory if you require proof the file is still present. The archive alone does not check whether a user later deleted or moved the media.

Catch DownloadError for extractor/download/post-processing failures, ValueError for rejected input and OSError for local filesystem failures. Treat these as distinct classes in your application logs. Error messages are useful diagnostics, but their text is not a stable structured taxonomy of every YouTube failure.

Complete script: resumable batch worker

Put download_batch.py beside download_video.py. Create a UTF-8 urls.txt with one video URL or ID per line. This intentionally runs sequentially, so one process owns the archive and output directory. It writes a completed, skipped or failed result for every attempted input and exits nonzero when any item failed.

download_batch.py
import argparse
import json
from datetime import datetime, timezone
from pathlib import Path

from yt_dlp.utils import DownloadError
from download_video import download_video


def run_batch(manifest, output):
    folder = Path(output).resolve()
    folder.mkdir(parents=True, exist_ok=True)
    sources = list(dict.fromkeys(
        line.strip()
        for line in Path(manifest).read_text(encoding="utf-8-sig").splitlines()
        if line.strip() and not line.lstrip().startswith("#")
    ))
    counts = {"completed": 0, "skipped": 0, "failed": 0}
    with (folder / "attempts.jsonl").open("a", encoding="utf-8") as log:
        for source in sources:
            try:
                result = download_video(source, folder)
            except (DownloadError, ValueError, OSError) as error:
                result = {"source": source, "status": "failed",
                          "error_type": type(error).__name__, "error": str(error)}
            result["recorded_at"] = datetime.now(timezone.utc).isoformat()
            log.write(json.dumps(result, ensure_ascii=False) + "\n")
            log.flush()
            counts[result["status"]] += 1
    return counts


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("manifest", help="UTF-8 file, one video URL or ID per line")
    parser.add_argument("--output", default="collection")
    args = parser.parse_args()
    counts = run_batch(args.manifest, args.output)
    print(json.dumps(counts, indent=2))
    raise SystemExit(1 if counts["failed"] else 0)
The append-only attempts.jsonl keeps retries as separate attempts. Duplicate lines within a manifest are removed; the download archive handles completed IDs across runs.
Run or resume the same batch
python download_batch.py urls.txt --output collection

Flush after each record so an interruption does not leave every result buffered until the end. There is still a small window between the library recording its archive and your application writing an attempt record. If a crash lands there, the next run can report skipped. For a service, reconcile the filesystem/archive with a durable job database instead of claiming this text-file example is transactional.

Keep attempts.jsonl private: errors can include source and request details. Report totals by status, inspect the failed items, and replay the same manifest after resolving a shared environment problem. Do not add every failed ID to the success archive.

Production: queue, deadlines and storage

YoutubeDL is synchronous. Running it directly inside an async web handler blocks that handler's event loop; even a thread offload does not make a browser request an appropriate lifetime for a large download. Accept the job, persist its source/options, and let a worker produce a final result.

  • Create a durable job ID before execution. Store the canonical video ID, output policy, attempt number and destination.
  • Use per-job working directories and a bounded worker pool. Do not share a YoutubeDL instance across concurrent jobs.
  • Use a separate process when you need a hard wall-clock deadline or cancellation; socket_timeout limits individual network operations, not the whole job.
  • If exposing user input over HTTP, accept supported YouTube video identifiers rather than arbitrary URLs, output paths, extractor arguments or shell snippets.
  • Record local-file readiness and cloud-upload completion separately; keep enough state to retry an upload without downloading again.
  • Keep FFmpeg, runtime, yt-dlp and plugin versions with your deployment. Exercise a small known workload before replacing a worker image.

A simple worker pool is a better starting point than unbounded asyncio.gather calls around many downloads. Coordinate total work across processes; each downloader's sleep settings do not regulate the whole service. Keep a separate retry budget for job attempts so application retries do not multiply the downloader's own retry count.

Troubleshoot the Python worker

ProblemCheck
Works in the CLI, fails in PythonCompare the actual options. YoutubeDL does not automatically load your CLI configuration file.
Progress says finished, file missingUse the after_move boundary and inspect post-processing errors.
Repeated source returns skippedRead the collection archive; use a different archive when changing output policies.
Worker hangs longer than socket_timeoutA job can perform many operations/retries. Add a process-level deadline if needed.
403 or bot checks on the serverUpdate nightly, check Deno, reduce concurrency and test a replacement exit IP when the route remains rejected.
429 in metadata / transcript jobsPause the affected IP, pace extraction/subtitle requests and add delays between metadata-only jobs.

When the output belongs in a cloud pipeline

If you want to own the downloader, the workflows above give you control over files, formats and processing. If your application needs completed media delivered to storage, FlashData provides tracked YouTube download jobs, bot handling, proxy routing and retries. Your application submits the source and output settings, then keeps the job ID and delivery record.