Skip to main content
The YoutubeDL class is the central component of yt-dlp’s Python API. It handles video downloading, information extraction, and coordination of extractors and post-processors.

Class Overview

from yt_dlp import YoutubeDL

ydl = YoutubeDL(params=None, auto_init=True)
params
dict
default:"{}"
Dictionary of options to configure the downloader behavior
auto_init
boolean | string
default:"true"
Whether to load default extractors and print header. Set to ‘no_verbose_header’ to skip header printing

Constructor Parameters

The params dictionary accepts numerous configuration options. Below are the most important ones:

Authentication

username
string
Username for authentication purposes
password
string
Password for authentication purposes
videopassword
string
Password for accessing a video
usenetrc
boolean
default:"false"
Use netrc for authentication instead

Output Options

outtmpl
string | dict
Output filename template. Can be a string or dictionary with keys ‘default’, ‘chapter’, etc.Example: '%(title)s.%(ext)s' or {'default': '%(title)s.%(ext)s'}
quiet
boolean
default:"false"
Do not print messages to stdout
verbose
boolean
default:"false"
Print additional info to stdout
no_warnings
boolean
default:"false"
Do not print out anything for warnings

Download Control

format
string | function
Video format code. See format selection documentation. Can also be a function that takes context and returns formats to download.Examples: 'best', 'bestvideo+bestaudio', 'worst[height>=480]'
skip_download
boolean
default:"false"
Skip the actual download of the video file
simulate
boolean
Do not download video files. If unset, simulate only if listing formats/subtitles/thumbnails
ignoreerrors
boolean | string
default:"false"
Do not stop on download errors. Can be ‘only_download’ to ignore only download errors
extract_flat
boolean | string
default:"false"
Do not resolve URLs further
  • False: Always process (default for API)
  • True: Never process
  • 'in_playlist': Do not process inside playlists
  • 'discard': Always process but don’t return result from playlists
  • 'discard_in_playlist': Same as discard but only for playlists (default for CLI)

Format Selection

format_sort
list
List of fields by which to sort video formats
format_sort_force
boolean
default:"false"
Force the given format_sort
allow_multiple_video_streams
boolean
default:"false"
Allow multiple video streams to be merged into a single file
allow_multiple_audio_streams
boolean
default:"false"
Allow multiple audio streams to be merged into a single file

Filesystem Options

paths
dict
Dictionary of output paths. Allowed keys are ‘home’, ‘temp’ and output template types
restrictfilenames
boolean
default:"false"
Do not allow ”&” and spaces in file names
windowsfilenames
boolean
Force filenames to be Windows compatible (true) or sanitize minimally (false)
overwrites
boolean
Overwrite all files if true, overwrite only non-video files if None, don’t overwrite if false

Metadata Options

writeinfojson
boolean
default:"false"
Write the video description to a .info.json file
writethumbnail
boolean
default:"false"
Write the thumbnail image to a file
writesubtitles
boolean
default:"false"
Write the video subtitles to a file
writeautomaticsub
boolean
default:"false"
Write automatically generated subtitles to a file
getcomments
boolean
default:"false"
Extract video comments (requires writeinfojson to write to disk)

Network Options

proxy
string
URL of the proxy server to use
socket_timeout
number
Time to wait for unresponsive hosts, in seconds
http_headers
dict
Dictionary of custom headers to be used for all requests
source_address
string
Client-side IP address to bind to
impersonate
ImpersonateTarget
Client to impersonate for requests

Post-Processing

postprocessors
list
List of post-processor dictionaries. Each must have a ‘key’ field with the post-processor name
keepvideo
boolean
default:"false"
Keep the video file after post-processing
ffmpeg_location
string
Path to the ffmpeg binary or its containing directory

Main Methods

download()

Download videos from a list of URLs.
def download(url_list: list[str]) -> int
url_list
list[str]
required
List of URLs to download
return
int
Exit code (0 for success, non-zero for errors)
Example:
with yt_dlp.YoutubeDL({'format': 'best'}) as ydl:
    error_code = ydl.download(['https://www.youtube.com/watch?v=dQw4w9WgXcQ'])
    if error_code != 0:
        print("Download failed")

extract_info()

Extract and return the information dictionary of a URL.
def extract_info(
    url: str,
    download: bool = True,
    ie_key: str | None = None,
    extra_info: dict | None = None,
    process: bool = True,
    force_generic_extractor: bool = False
) -> dict | None
url
string
required
URL to extract information from
download
boolean
default:"true"
Whether to download videos
ie_key
string
Use only the extractor with this key (e.g., ‘Youtube’, ‘Generic’)
process
boolean
default:"true"
Whether to resolve all unresolved references (URLs, playlist items). Must be True for download to work
extra_info
dict
Dictionary containing extra values to add to the info (for internal use)
force_generic_extractor
boolean
default:"false"
Force using the generic extractor (deprecated, use ie_key=‘Generic’)
return
dict | None
Information dictionary containing video metadata and formats
Example:
with yt_dlp.YoutubeDL({}) as ydl:
    info = ydl.extract_info('https://www.youtube.com/watch?v=dQw4w9WgXcQ', download=False)
    
    print(f"Title: {info['title']}")
    print(f"Duration: {info['duration']}")
    print(f"Formats available: {len(info['formats'])}")

add_post_processor()

Add a post-processor to the downloader.
def add_post_processor(pp: PostProcessor, when: str = 'post_process') -> None
pp
PostProcessor
required
Post-processor instance to add
when
string
default:"post_process"
When to run the post-processor. Valid values: ‘pre_process’, ‘after_filter’, ‘before_dl’, ‘post_process’, ‘after_move’, ‘after_video’, ‘playlist’
Example:
from yt_dlp.postprocessor import FFmpegExtractAudioPP

with yt_dlp.YoutubeDL({}) as ydl:
    ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec='mp3'))
    ydl.download(['https://www.youtube.com/watch?v=dQw4w9WgXcQ'])

add_progress_hook()

Add a callback function for download progress updates.
def add_progress_hook(ph: callable) -> None
ph
callable
required
Function that receives a dictionary with progress information
The progress hook receives a dictionary with these keys:
  • status: One of “downloading”, “error”, or “finished”
  • filename: Final filename
  • downloaded_bytes: Bytes downloaded so far
  • total_bytes: Total size of the file
  • speed: Download speed in bytes/second
  • eta: Estimated time remaining
Example:
def my_hook(d):
    if d['status'] == 'downloading':
        print(f"Downloading: {d['_percent_str']} at {d['_speed_str']}")
    elif d['status'] == 'finished':
        print(f"Done downloading {d['filename']}")

with yt_dlp.YoutubeDL({}) as ydl:
    ydl.add_progress_hook(my_hook)
    ydl.download(['https://www.youtube.com/watch?v=dQw4w9WgXcQ'])

Context Manager

The YoutubeDL class supports context manager protocol:
with yt_dlp.YoutubeDL(params) as ydl:
    # Use ydl here
    ydl.download(urls)
# Cleanup happens automatically
This ensures proper cleanup of resources like cookies and temporary files.

Class Methods

validate_outtmpl()

Validate an output template string.
@staticmethod
def validate_outtmpl(outtmpl: str) -> str | None
Returns an error message if the template is invalid, or None if valid.

Utility Methods

to_screen()

Print a message to the screen output.
def to_screen(message: str, skip_eol: bool = False, quiet: bool = None) -> None

report_warning()

Report a warning message.
def report_warning(message: str, only_once: bool = False) -> None

report_error()

Report an error message.
def report_error(message: str) -> None

write_debug()

Write a debug message.
def write_debug(message: str, only_once: bool = False) -> None

Example: Complete Configuration

import yt_dlp

ydl_opts = {
    # Format selection
    'format': 'bestvideo[height<=1080]+bestaudio/best[height<=1080]',
    
    # Output template
    'outtmpl': '%(title)s.%(ext)s',
    
    # Filesystem
    'restrictfilenames': True,
    'overwrites': False,
    
    # Metadata
    'writeinfojson': True,
    'writethumbnail': True,
    'writesubtitles': True,
    'subtitleslangs': ['en'],
    
    # Download control
    'ignoreerrors': 'only_download',
    'no_warnings': False,
    'quiet': False,
    
    # Post-processing
    'postprocessors': [{
        'key': 'FFmpegExtractAudio',
        'preferredcodec': 'mp3',
        'preferredquality': '192',
    }],
    
    # Network
    'socket_timeout': 30,
}

with yt_dlp.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=dQw4w9WgXcQ'])

Build docs developers (and LLMs) love