Skip to navigation

Should video_id contain the entire YouTube URL?

No. Pass only the 11-character YouTube video ID in video_id, never the full URL. Extract video_id from the v query parameter of a watch URL or from the path of a youtu.be link—for example, https://www.youtube.com/watch?v=AbCdEfGhI_1 maps to AbCdEfGhI_1. Deduplicate different links pointing to the same video_id locally before fetching page one of comments.

For a product-review study, normalize the selected YouTube links before making any API call:

  • A /watch URL stores the 11-character ID in the v query parameter.
  • A youtu.be link stores the 11-character ID directly in the path.
  • /embed/, /shorts/, and /live/ paths also carry the 11-character video ID.
  • Playlist-only URLs, channel handles, and redirect links do not contain an unambiguous video ID.

youtube_ids.py below parses only these explicit URL forms locally without making network requests and does not enumerate playlists or channels.

Save the link strings in links.json. The sample input below includes two URL forms for the same 11-character ID plus one channel handle; the sample ID is not a verified playable video:

["https://www.youtube.com/watch?v=AbCdEfGhI_1&list=example", "https://youtu.be/AbCdEfGhI_1?t=30", "https://www.youtube.com/@example"]

Save the script as youtube_ids.py and run python3 youtube_ids.py links.json youtube-prepared. youtube_ids.py preserves letter case and underscores, rejects ambiguous duplicate v parameters, and deduplicates by the exact 11-character video_id rather than by title or channel name. requests.json is a list of separate Capabilities Run request bodies, not a batch API request.

import json,pathlib,re,sys
from urllib.parse import urlsplit,parse_qs
source,target=map(pathlib.Path,sys.argv[1:3])
inputs=json.loads(source.read_text(encoding='utf-8'))
if not isinstance(inputs,list) or not 1<=len(inputs)<=100: raise ValueError('Supply 1–100 strings')
pattern=re.compile(r'[A-Za-z0-9_-]{11}')
ids,rejected={},[]
for n,value in enumerate(inputs,1):
identifier=None
if isinstance(value,str):
text=value.strip()
if pattern.fullmatch(text): identifier=text
else:
try:
u=urlsplit(text);query=parse_qs(u.query,keep_blank_values=True)
short=re.fullmatch(r'/([A-Za-z0-9_-]{11})/?',u.path)
direct=re.fullmatch(r'/(?:embed|shorts|live)/([A-Za-z0-9_-]{11})/?',u.path)
safe=u.scheme=='https' and not u.username and not u.password and u.port in (None,443)
if safe and u.hostname=='youtu.be' and short: identifier=short.group(1)
elif safe and u.hostname in ('youtube.com','www.youtube.com','m.youtube.com'):
if u.path=='/watch' and len(query.get('v',[]))==1: identifier=query['v'][0]
elif direct: identifier=direct.group(1)
if not isinstance(identifier,str) or not pattern.fullmatch(identifier): identifier=None
except ValueError: identifier=None
if identifier is None:
rejected.append({'input_index':n,'input':value,'reason':'no_unambiguous_supported_video_id'});continue
ids.setdefault(identifier,[]).append({'input_index':n,'input':value})
requests=[{'reference':'data:youtube.web_v2.get_video_comments','input':{'video_id':i,'sort_by':'newest','country_code':'US','language_code':'en-US','need_format':True},'view':'full'} for i in ids]
target.mkdir(parents=True,exist_ok=False)
(target/'requests.json').write_text(json.dumps(requests,ensure_ascii=False,indent=2),encoding='utf-8')
(target/'audit.json').write_text(json.dumps({'sources':ids,'rejected':rejected,'unique_ids':len(ids),'network_calls':0,
'existence_or_access_verified':False,'example_first_page_cost_usd':format(len(ids)*3/1000,'.3f')},ensure_ascii=False,indent=2),encoding='utf-8')
print(json.dumps({'unique_ids':len(ids),'rejected':len(rejected),'network_calls':0}))

Audit prepared requests and execution boundaries

Inspect audit.json before sending any request:

  1. A rejected channel profile or playlist requires choosing a specific video URL manually; never truncate a URL to 11 characters.
  2. A /watch URL carrying both v and list targets only that single video; list and timestamp parameters do not trigger a playlist scan.
  3. Distinct URLs resolving to the same video_id collapse into one request, while distinct video_id values never merge even if video titles match.

Valid 11-character syntax does not prove that a video exists, is public, has comments enabled, or will return data.

Each prepared body in requests.json sets sort_by:"newest", language_code:"en-US", country_code:"US", and need_format:true, and omits continuation_token because the call requests page one. Those parameters define collection settings rather than an English-only filter or proof of US commenters. If a study needs different settings, update the parameters before starting and keep them fixed across subsequent pages. At the current action rate of $0.003 per executed request, 10 unique first pages cost $0.030, excluding later pages, replies, and analysis; verify the contract and budget before execution.

youtube_ids.py sends no requests. Once approved, send each reviewed body in requests.json separately to /v1/capabilities/run and keep both the response and request settings. youtube_ids.py does not parse YouTube comments or handle continuation fields. If every link is rejected, the empty requests.json list signals that the inputs need correction rather than a completed export.

Recover a saved preview · Comment research