I am trying to use youtube's api to get the subscriber count of a channel by it's channel name using node.js. How do i do that?
You can use the official YouTube API channels.list method to get statistics like: subscriberCount, videoCount and viewCount.
| Get statistics from a YouTube channel | Run in Fusebit |
|---|
const youtube = googleClient.youtube('v3');
const channelName = 'GoogleDevelopers';
const channelsResponse = await youtube.channels.list({
part: 'id,statistics',
forUsername: channelName,
});
if (channelsResponse.data.items && channelsResponse.data.items.length) {
const { statistics: { subscriberCount, videoCount, viewCount } } = channelsResponse.data.items[0];
console.log(`The channel ${channelName} has 🧑🏾🤝🧑🏾 ${subscriberCount} subscribers, 🎬 ${videoCount} videos and 👀 ${viewCount} views.`);
} else {
console.log = `Channel not found: ${channelName}`;
}
[Update]
Based on the comments, here is an example of how to search for a channel based on a search term, then you will use the channel id to get the statistics, from the previous code, instead of sending forUserName parameter you will send id See search API docs here
const channelsResponse = await youtube.search.list({
part: 'snippet',
q: searchTerm,
maxResults: 10,
type: 'channel',
order: 'viewCount' // show more popular first
});
This is the response object returned by each item from the search
{
"kind": "youtube#searchResult",
"etag": etag,
"id": {
"kind": string,
"videoId": string,
"channelId": string,
"playlistId": string
},
"snippet": {
"publishedAt": datetime,
"channelId": string,
"title": string,
"description": string,
"thumbnails": {
(key): {
"url": string,
"width": unsigned integer,
"height": unsigned integer
}
},
"channelTitle": string,
"liveBroadcastContent": string
}
}