Currently, I am attempting to create a JSON object that represents the views per video for a specific YouTube user.
To achieve this, I start by making an API call to retrieve all the video IDs from a designated channel, storing them in an empty array. Subsequently, I iterate through each video ID to make multiple API calls for individual videos in order to collect data about their respective views.
At present, each video requires its own API call and I am facing challenges in consolidating all the data retrieved from these calls into a single object.
I recognize that there might be a more efficient approach to address this issue, and I am seeking recommendations on how to better handle this situation.
Thank you!
var channelId = 'UCO1cgjhGzsSYb1rsB4bFe4Q'
var url = 'https://www.googleapis.com/youtube/v3/search?key=' + apiKey + '&channelId=' + channelId + '&part=snippet,id&order=date&maxResults=20'
fetch(url).then((resp) => resp.json()).then(function(data) {
var videoIds = []
for (var i = 0; i < data.items.length; i++) {
videoIds.push(data.items[i].id.videoId)
}
return videoIds
}).then(function(ids) {
var urls = []
for (var i = 0; i < ids.length; i++) {
urls.push('https://www.googleapis.com/youtube/v3/videos?part=statistics&id=' + ids[i] + '&key=' + apiKey)
}
return urls
}).then(function(urls) {
for (var i = 0; i < urls.length; i++) {
fetch(urls[i]).then((resp) => resp.json()).then(function(data) {
console.log(data)
})
}
update
I found a solution to this problem by utilizing another fetch URL along with the d3.json function.
var search = 'https://www.googleapis.com/youtube/v3/search?key=' + apiKey + '&channelId=' + channelId + '&part=snippet,id&order=date&maxResults=5'
var videoIds = []
fetch(search).then((resp) => resp.json())
.then(function(data) {
for (var i = 0; i < data.items.length; i++) {
videoIds.push(data.items[i].id.videoId)
}
return fetch("https://www.googleapis.com/youtube/v3/videos?id=" +videoIds + "&part=snippet%2CcontentDetails%2Cstatistics&key=" + apiKey);
}).then(function(response) {
d3.json(response.url, function(error, data) {
if (error) throw error;
console.log(data)