# yt-dlp Python API

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

Canonical reference: https://flashdata.dev/docs/guides/yt-dlp-python-api
Reviewed: 2026-11-13 by FlashData

- [Start with Python](https://flashdata.dev/docs/guides/yt-dlp-python-api/reference.md#first-call) — Install and make one call
- [Find the final file](https://flashdata.dev/docs/guides/yt-dlp-python-api/reference.md#completion) — After transfer and processing
- [Get the worker](https://flashdata.dev/docs/guides/yt-dlp-python-api/reference.md#worker) — Runnable .py download
- [Process a collection](https://flashdata.dev/docs/guides/yt-dlp-python-api/reference.md#batch) — Per-source results and recovery

<a id="setup"></a>

## Install the Python library


**In your Python 3.11+ environment**

```bash
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.

- [Install external dependencies](https://flashdata.dev/docs/guides/how-to-use-yt-dlp/reference.md#install)
- [Upstream embedding reference](https://github.com/yt-dlp/yt-dlp#embedding-yt-dlp)

<a id="first-call"></a>

## Download your first video


**Download one video**

```python
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.

> **Python options are not mechanical translations of flags**
> --write-info-json maps to writeinfojson; --no-playlist maps to noplaylist. Audio conversion uses a postprocessors list. Consult YoutubeDL's parameter documentation or the upstream cli_to_api.py helper instead of guessing option names.

<a id="metadata"></a>

## Read metadata without media


**Export a small metadata record**

```python
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.

<a id="options"></a>

## Python option reference


| Task | Python option | Detail |
| --- | --- | --- |
| 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": True | Keeps 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": False | Lets 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**

```python
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.

- [Python parameter reference](https://github.com/yt-dlp/yt-dlp/blob/master/yt_dlp/YoutubeDL.py)
- [Convert CLI options to Python options](https://github.com/yt-dlp/yt-dlp/blob/master/devscripts/cli_to_api.py)

<a id="dataset"></a>

## 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**

```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 finishes | What the dataset record needs |
| --- | --- |
| Check the final MP4 with ffprobe | Video/audio codecs, duration, dimensions, file path and byte count. |
| Check caption sidecars separately | Language, supplied/automatic track, timestamps and whether the file actually exists. |
| No matching captions available | Keep the media and mark text missing; send audio to your transcription stage if required. |
| Captions hit 429 | Retry 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.

- [CLI recipe and dataset inventory](https://flashdata.dev/docs/guides/how-to-use-yt-dlp/reference.md#dataset)
- [Pace Python metadata and captions](https://flashdata.dev/docs/guides/yt-dlp-429-too-many-requests/reference.md#python)

<a id="completion"></a>

## 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.

| Stage | What you know | Application state |
| --- | --- | --- |
| Downloading | Some media bytes are arriving. | running |
| Transfer hook: finished | This transfer ended; processing can still follow. | processing |
| after_move post-processor | The file has passed the configured post-processing and final move. | local file ready |
| Upload and integrity check | Your 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.

> **A completed local download is not a completed cloud delivery**
> If the next step uploads the file, keep an upload state separately. A download archive can skip a source on the next run even when the previous upload failed. Retry the upload from the saved local file and job record.

<a id="worker"></a>

## 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 download_video.py](https://flashdata.dev/examples/yt-dlp/download_video.py)

**download_video.py**

```python
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**

```bash
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.

<a id="batch"></a>

## 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 download_batch.py](https://flashdata.dev/examples/yt-dlp/download_batch.py)

**download_batch.py**

```python
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**

```bash
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.

<a id="service"></a>

## 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.

<a id="diagnostics"></a>

## Troubleshoot the Python worker


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

- [403 diagnostic workflow](https://flashdata.dev/docs/guides/yt-dlp-403-forbidden/reference.md)
- [Session and bot-check workflow](https://flashdata.dev/docs/guides/yt-dlp-sign-in-not-a-bot/reference.md)
- [429 recovery and Python pacing](https://flashdata.dev/docs/guides/yt-dlp-429-too-many-requests/reference.md)
- [Inspect the saved media](https://flashdata.dev/docs/guides/how-to-use-yt-dlp/reference.md#verify)

<a id="managed-downloads"></a>

## 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.

- [Compare the two operating models](https://flashdata.dev/docs/guides/flashdata-vs-yt-dlp/reference.md)
- [Bulk YouTube video downloads](https://flashdata.dev/products/youtube-download#bulk-downloads)
- [Try the download demo](https://flashdata.dev/products/youtube-download#playground)
- [Download API reference](https://flashdata.dev/docs/sources/youtube_download/reference.md)
