如何使用视频ID数组调用YouTube API的videos.list接口?
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

