Solving PyTube HTTP 400 Bad Request Error
Problem Statement
Users encounter the HTTP Error 400: Bad Request when downloading long YouTube videos (approximately 100+ minutes) with PyTube. This error occurs despite the code working perfectly for shorter videos and previously functioning correctly. The core issue arises from YouTube's API changes that invalidate older PyTube authentication requests, particularly affecting videos with certain characteristics like length or region restrictions.
Symptoms include:
HTTP Error 400: Bad Request
tracebacks originating fromurllib
- Failures only on long-duration videos (~100 minutes)
- Successful downloads of shorter videos with identical code
- Sudden appearance of errors without code changes
Recommended Solutions
1. Switch to pytubefix (Recommended Approach)
pytubefix
is an actively maintained fork that addresses PyTube's API compatibility issues.
# Install the fixed library
pip install pytubefix
# Modified code using pytubefix
from pytubefix import YouTube
youtubeObject = YouTube('https://www.youtube.com/watch?v=DASMWPUFFP4')
youtubeObject = youtubeObject.streams.get_highest_resolution()
youtubeObject.download('D:\\Utakmice')
Key advantages:
- Drop-in replacement for PyTube (minimal code changes)
- Actively maintained with YouTube API updates
- Resolves the HTTP 400 error for long videos
- Preserves all PyTube functionality
Maintenance Note
This fork has addressed 15+ PyTube issues in 2024 alone. Check pytubefix on PyPI for updates.
2. Patch Original PyTube
Manually modify PyTube's innertube.py
client configuration (temporary fix until update):
- Locate
innertube.py
in your PyTube installation (typically insite-packages/pytube
) - Find the following line:
def __init__(self, client='ANDROID', use_oauth=False, allow_cache=True):
- Change to:
def __init__(self, client='WEB', use_oauth=False, allow_cache=True):
Pros/Cons:
✓ Quick fix without library change
✘ Requires re-patching after PyTube updates
✘ May break with future YouTube API changes
Version Warning
This fix applies to PyTube versions up to 15.0.0. Check GitHub Issue #1894 for latest patches.
3. Use yt-dlp Alternative
For future-proof downloading, consider yt-dlp
—an actively maintained YouTube downloader:
# Installation
pip install yt-dlp
# Download implementation
import yt_dlp
def download_video(url):
ydl_opts = {
'outtmpl': 'D:/Utakmice/%(title)s.%(ext)s', # Custom output path
'format': 'bestvideo+bestaudio/best' # Best resolution
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
# Usage
download_video('https://www.youtube.com/watch?v=DASMWPUFFP4')
Benefits:
- Actively maintained (fixes within hours of YouTube changes)
- Supports advanced features (formats, metadata, error recovery)
- 300+ site integrations beyond YouTube
- More reliable for long/live videos
Problem Explanation
The HTTP 400 error occurs due to PyTube's outdated API request headers when interacting with YouTube's InnerTube API. YouTube periodically changes validation requirements, causing older clients like PyTube's default ANDROID
credentials to be rejected. Long videos trigger additional validation checks that expose these outdated configurations.
Key technical details:
- PyTube sends requests with deprecated client parameters (
client="ANDROID"
) - YouTube returns
400 Bad Request
for authentication mismatches - Fixes involve updating client parameters (
client="WEB"
) or library internals - Alternative libraries like
yt-dlp
implement auto-updating client logic
Best Practices
Avoid modifying library source files
Prefer maintained forks likepytubefix
over manual patches for future stabilityAdd error recovery
Implement retry logic for temporary network issues:
# Retry example
from pytubefix import YouTube
from urllib.error import HTTPError
import time
try:
YouTube(url).streams.first().download()
except HTTPError as e:
if e.code == 400:
print("Retrying after API error...")
time.sleep(5)
# Add fallback logic here
- Regularly update dependencies
Monitor library update channels for compatibility fixes:
# Check for updates weekly
pip list --outdated
- Verify video availability
Test with multiple videos to rule out content-specific restrictions
Final Recommendation:
Migrate to pytubefix
for minimal code changes combined with active maintenance. For new projects, consider yt-dlp
for its robust feature set and faster issue resolution cycle. Monitor PyTube's GitHub issues for future core library updates.