Developer guide
How to use yt-dlp in Python (the YoutubeDL API)
yt-dlp is not just a CLI — it is a Python package, and the command-line tool is a thin wrapper around it. If you are writing Python, skip the subprocess gymnastics and import it directly: you get the same downloader, plus structured metadata as plain dicts instead of parsed stdout.
Quick answer
pip install "yt-dlp[default]"from yt_dlp import YoutubeDL
with YoutubeDL({"format": "bv*+ba/b"}) as ydl:
ydl.download(["https://www.youtube.com/watch?v=..."])That is a complete yt-dlp Python example: best video plus best audio, merged, saved to the current directory. Everything else is configuration on the options dict.
Extract info without downloading
Most integrations want metadata first — title, duration, available formats — before deciding whether to download anything. Pass download=False:
from yt_dlp import YoutubeDL
with YoutubeDL() as ydl:
info = ydl.extract_info(url, download=False)
print(info["title"], info["duration"])The returned dict contains internal objects that will not serialize. If you need to store or return it as JSON, run it through ydl.sanitize_info(info) first — that is what the CLI's -J flag does internally. Full walkthrough in the metadata guide.
The options dict is the CLI flags
Every CLI flag maps to a key in the dict you pass to YoutubeDL. If you know the command line, you already know the library:
opts = {
"format": "bv*+ba/b", # -f
"outtmpl": "%(uploader)s/%(title)s.%(ext)s", # -o
"quiet": True, # -q, silence progress output
"noplaylist": True, # --no-playlist, single video only
}
with YoutubeDL(opts) as ydl:
ydl.download([url])The authoritative list is the docstring of the YoutubeDL class in the yt-dlp source — it documents every key, and it is more current than any blog post.
Get the path of the downloaded file
An app usually needs to know where the file landed so it can upload it, store it or hand it to the next step. Don't rebuild the name from the template yourself; read it from the info dict that extract_info returns, or from a progress hook:
from yt_dlp import YoutubeDL
def on_progress(d):
if d["status"] == "finished":
print("downloaded", d["filename"])
opts = {
"outtmpl": "%(id)s.%(ext)s",
"quiet": True,
"noprogress": True,
"progress_hooks": [on_progress],
}
with YoutubeDL(opts) as ydl:
info = ydl.extract_info(url, download=True)
path = info["requested_downloads"][0]["filepath"] # absolute pathThe hook fires for every file yt-dlp writes, so when video and audio are downloaded separately and merged you see each part finish. requested_downloads holds the final, merged file. Progress hooks are also how you report percent done to a job dashboard: the dict has downloaded_bytes and total_bytes while status is "downloading".
Error handling
Downloads fail for reasons outside your control — private videos, geo blocks, extractor breakage, throttling. yt-dlp raises DownloadError for all of them:
from yt_dlp import YoutubeDL
from yt_dlp.utils import DownloadError
try:
with YoutubeDL({"format": "bv*+ba/b"}) as ydl:
ydl.download([url])
except DownloadError as e:
log.warning("import failed for %s: %s", url, e)
# decide: retry, skip, or surface to the useryt-dlp retries individual HTTP fragments internally, but job-level retry logic — backoff, dead-letter queues, alerting — belongs in your code. Treat every download as an operation that can fail and your integration will survive the days when an extractor is broken upstream.
Library vs subprocess
Importing the library is the cleanest integration, but shelling out to the CLI is sometimes the more robust choice, and it is worth being honest about when:
- • Version pinning conflicts.yt-dlp needs to be updated constantly; your app's other dependencies may not want to move. A standalone binary updates independently of your virtualenv.
- • Isolation. A crashed or hung download in a subprocess cannot take your worker down with it, and you can kill it with a plain timeout.
- • Non-Python callers. From Node, Go, or Rust, subprocess plus
-Joutput is the only option — see the API guide.
For scripts and single-purpose tools, import the library. For long-running services where a yt-dlp update should not require redeploying your app, subprocess earns its awkwardness.
The mistake to avoid
Do not treat a working yt-dlp embed as done. Extractor code has a shelf life measured in weeks — sites change their players and yt-dlp ships counter-fixes on a rolling basis. The moment you import it, your app inherits that update treadmill, plus YouTube's bot checks when you run from datacenter IPs. Budget for keeping yt-dlp current and for handling "it worked yesterday" failures, or the integration will quietly rot.
If your app only needs the finished file or a transcript, you can hand that part off instead. This Python guide does it with one requests call to a hosted API, with error codes and a FastAPI webhook, and it works from servers where datacenter IPs get blocked.
Automation
Running this on a schedule? See the API version.
Paste a link and watch one API call do what your batch script does — extraction, retries, and site breakage handled.
Building this into an app? See the API your backend calls instead
Frequently asked questions
Does yt-dlp have a Python API?
Yes. pip install yt-dlp, then import YoutubeDL from yt_dlp. The command-line tool is a wrapper around the same class, so anything the CLI does is available from Python with an options dict.
Where are the yt-dlp Python options documented?
In the docstring of the YoutubeDL class in yt_dlp/YoutubeDL.py. It lists every key the options dict accepts. The keys often don't match the flag names (-o is outtmpl, --no-playlist is noplaylist), so check there instead of guessing.
How do I get the downloaded file name in yt-dlp Python?
Call extract_info(url, download=True) and read info['requested_downloads'][0]['filepath'], which is the final file after any merge. A progress hook with status 'finished' also gives you each file as it is written.
Can I call yt-dlp from a Flask, Django or FastAPI request?
You can, but don't do it inside the request. A download can take minutes and fail halfway, so put it on a job queue (Celery, RQ, a background worker), create one YoutubeDL per job, and send the result back by polling or a webhook.
Why does my yt-dlp Python code work locally but fail on the server?
The library behaves exactly like the CLI, so a cloud server gets the same bot checks and 403s from YouTube that the command line does on a datacenter IP. Keep yt-dlp updated and see the server guide for the free fixes.