How Does Pyutube Validate YouTube URLs: Inside the URLHandler Class

Pyutube validates YouTube URLs through the URLHandler class in pyutube/handlers/URLHandler.py, which uses a multi-stage regex-based pipeline to detect raw video IDs, standard videos, shorts, and playlists before allowing any download operations to proceed.

The hetari/pyutube library implements a rigorous validation system to ensure only legitimate YouTube content URLs are processed. Understanding how Pyutube validates YouTube URLs helps developers debug link issues and ensures reliable video downloading workflows.

The URLHandler Architecture

The validation logic resides entirely within the URLHandler class in pyutube/handlers/URLHandler.py. This class acts as the gatekeeper for all incoming URLs, transforming raw video IDs into full URLs and categorizing links into three distinct types: "video", "short", or "playlist".

The public interface exposes a single validate() method that orchestrates the entire validation chain. This method first checks for standalone video IDs, normalizes them into full watch URLs if necessary, then delegates to private helper methods that apply specific regex patterns for different YouTube URL formats.

Step-by-Step Validation Process

Raw Video-ID Detection

Pyutube accepts direct 11-character video IDs in addition to full URLs. The __is_youtube_video_id method (lines 9-21) checks if the input string is exactly 11 characters long and contains only valid YouTube ID characters ([a-zA-Z0-9_-]).

If this check passes, the handler automatically prepends https://www.youtube.com/watch?v= to convert the raw ID into a standard watch URL before proceeding to link classification.

The __is_youtube_link method (lines 34-53) serves as the routing dispatcher. It examines the normalized URL and determines whether it represents a video, short, or playlist by delegating to specialized detection methods.

This method returns a boolean indicating validity and helps route the URL to the appropriate specific validator.

Shorts Pattern Matching

YouTube Shorts use a distinct URL structure that requires dedicated detection. The __is_youtube_shorts method (lines 65-68) applies a comprehensive regex pattern:

r"(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|shorts\/|watch\?.*?v=))(?:(?:[^\/\n\s]+\/)?)([a-zA-Z0-9_-]+)"

This pattern captures short URLs (/shorts/), standard watch URLs with parameters, and embedded forms. It extracts the video ID regardless of which Shorts URL format the user provides.

Video Pattern Matching

For standard YouTube videos, the __is_youtube_video method (lines 88-92) implements a stricter regex that enforces the 11-character ID requirement:

r"^(?:https?://)?(?:www\.)?(?:youtube(?:-nocookie)?\.com/(?:(watch\?v=|watch\?feature\=share\&v=)|embed/|v/|live_stream\?channel=|live/)|youtu\.be/)([a-zA-Z0-9_-]{11})"

This regex handles multiple YouTube domain variations including youtube-nocookie.com, youtu.be short links, embed URLs, and live stream URLs, ensuring the video ID is exactly 11 characters as per YouTube's specification.

Playlist Detection

The __is_youtube_playlist method (lines 94-107) recognizes playlist-only URLs and watch URLs containing list= parameters. It uses two distinct patterns to cover both the dedicated playlist endpoint and playlist parameters appended to individual video URLs.

This allows Pyutube to handle bulk downloads when users provide playlist URLs rather than individual video links.

Final Validation and Error Handling

The __validate_link method (lines 16-33) serves as the final gatekeeper. It calls __is_youtube_link and handles the validation result:

  • If validation fails, the method prints an error message and exits the program
  • If validation succeeds, it returns a tuple (<bool>, <type>) where the boolean indicates success and the type string is "video", "short", or "playlist"

This strict error handling prevents invalid URLs from reaching the download pipeline, ensuring robust operation.

Using URLHandler in Practice

The URLHandler class supports multiple input formats. Here are practical examples demonstrating how Pyutube validates YouTube URLs:

from pyutube.handlers import URLHandler

# Full YouTube watch URL (valid video)

handler = URLHandler("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
is_valid, link_type = handler.validate()
print(is_valid, link_type)   # → True video

# Shorts URL detection

handler = URLHandler("https://www.youtube.com/shorts/dQw4w9WgXcQ")
print(handler.validate())   # → (True, 'short')

# Playlist validation

handler = URLHandler(
    "https://www.youtube.com/playlist?list=PLynG8gQD-n8BMplEGyFBRVJFssMFo5x07"
)
print(handler.validate())   # → (True, 'playlist')

# Raw 11-character video ID

handler = URLHandler("dQw4w9WgXcQ")
print(handler.validate())   # → (True, 'video')

The handler normalizes raw IDs automatically, so users can paste either full URLs or just the video ID string interchangeably.

Summary

  • Multi-stage validation: Pyutube uses URLHandler in pyutube/handlers/URLHandler.py to apply progressively specific regex patterns for different YouTube URL types.
  • ID normalization: Raw 11-character video IDs are automatically converted to full watch URLs via __is_youtube_video_id.
  • Format coverage: The validation system handles standard videos, Shorts, playlists, embed URLs, nocookie domains, and youtu.be short links.
  • Strict enforcement: Invalid URLs trigger immediate error messages and program termination through __validate_link, protecting the download pipeline from malformed inputs.

Frequently Asked Questions

What regex pattern does Pyutube use to detect YouTube Shorts?

Pyutube detects Shorts using the pattern r"(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|shorts\/|watch\?.*?v=))(?:(?:[^\/\n\s]+\/)?)([a-zA-Z0-9_-]+)" implemented in the __is_youtube_shorts method. This regex captures /shorts/ paths, standard watch URLs with Shorts content, and various embedded forms while extracting the video ID.

Can Pyutube validate a raw video ID without the full URL?

Yes. The __is_youtube_video_id method checks if the input is exactly 11 characters matching [a-zA-Z0-9_-]. If so, Pyutube treats it as a video ID and internally converts it to https://www.youtube.com/watch?v=<id> before proceeding with standard validation.

What happens when Pyutube encounters an invalid YouTube URL?

The __validate_link method handles invalid URLs by printing an error message and calling sys.exit() to terminate the program immediately. This prevents any download operations from proceeding with malformed or non-YouTube URLs.

Does Pyutube support YouTube playlist validation?

Yes. The __is_youtube_playlist method (lines 94-107) validates both dedicated playlist URLs (/playlist?list=) and watch URLs containing list= parameters. Upon validation, it returns (True, 'playlist'), enabling the downloader to handle bulk video collections appropriately.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →