Skip to content

Instantly share code, notes, and snippets.

@ErickWendel
Created September 16, 2021 20:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ErickWendel/7ee9b41e94687d6af98712babe8a56dd to your computer and use it in GitHub Desktop.
Save ErickWendel/7ee9b41e94687d6af98712babe8a56dd to your computer and use it in GitHub Desktop.
Example of how to get video views from youtube
const YOUTUBE_KEY = "YOUR YOUTUBE KEY"
import axios = from 'axios';
function getVideoId(link) {
const videoId = link.match(/v=(?<videoId>.*)/)?.groups?.videoId
return videoId
}
async function getVideoViews(link) {
const videoId = getVideoId(link)
if (!videoId) {
console.error(`videoId not found!`, link)
return;
}
const url = `https://www.googleapis.com/youtube/v3/videos?part=statistics&id=${videoId}&key=${YOUTUBE_KEY}`
const { data: file } = await axios.get(url)
const views = file.items[0]?.statistics.viewCount
return views
}
const videoUrl = 'https://youtu.be/jBBrFyy77qQ'
const result = await getVideoViews(videoUrl)
console.log(result);
/*
{
"kind": "youtube#videoListResponse",
"etag": "fyh85_rYG0nXJ4gtxp-8eOeJbcQ",
"items": [
{
"kind": "youtube#video",
"etag": "fyiikzMjruhyNZp9yh8WoQX18BY",
"id": "Qq7mpb-hCBY",
"statistics": {
"viewCount": "320070",
"likeCount": "1885",
"dislikeCount": "77",
"favoriteCount": "0",
"commentCount": "1"
}
}
],
"pageInfo": {
"totalResults": 1,
"resultsPerPage": 1
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment