You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用视频ID数组调用YouTube API的videos.list接口?

How to Use an Array of Video IDs with YouTube API's videos.list in Ruby

Question

I'm working with the YouTube API, specifically the video items feature. Here's my current code:

# Sample ruby code for videos.list, in order to get tags and categoryId for a specific video 
def videos_list_multiple_ids(service, part, **params)
  params = params.delete_if { |p, v| v == ''}
  response = service.list_videos(part, params)
  print_results(response)
end
videos_list_multiple_ids(service, 'snippet', id: 'DTTwp6J47Sw, xSY75qJ_kIk')

Currently, the id parameter is passed as a comma-separated string of multiple video IDs, but I now have an array containing multiple video IDs. How can I modify the code to use this array to make the API request?
Thanks for your help.


Answer

Hey there! The fix here is really straightforward—since the YouTube API expects the id parameter to be a comma-separated string, we just need to convert your array into that format. Here are two clean approaches:

1. Convert the array at call time (no method changes needed)

If you want to keep your existing method as-is, just use Ruby's join(',') method to turn your array into the required comma-separated string when you call the function:

# Your array of video IDs
video_ids = ['DTTwp6J47Sw', 'xSY75qJ_kIk']

# Pass the converted string to the method
videos_list_multiple_ids(service, 'snippet', id: video_ids.join(','))

This is a quick, minimal change that works perfectly if you only need to handle arrays in specific calls.

2. Update the method to handle both arrays and strings

For a more robust solution that lets you pass either an array or a string to the id parameter, modify your method to automatically convert arrays to the correct format:

def videos_list_multiple_ids(service, part, **params)
  # Convert id array to comma-separated string if it's an array
  params[:id] = params[:id].join(',') if params[:id].is_a?(Array)
  
  params = params.delete_if { |p, v| v == ''}
  response = service.list_videos(part, params)
  print_results(response)
end

# Now you can pass an array directly
video_ids = ['DTTwp6J47Sw', 'xSY75qJ_kIk']
videos_list_multiple_ids(service, 'snippet', id: video_ids)

# Or still use the original comma-separated string if needed
videos_list_multiple_ids(service, 'snippet', id: 'DTTwp6J47Sw, xSY75qJ_kIk')

This makes your method more flexible, so you don't have to remember to convert arrays every time you call it.

Either way, the core idea is matching what the YouTube API expects: a single string with IDs separated by commas.


内容的提问来源于stack exchange,提问作者Dede Banell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:09:23