Created
September 16, 2021 20:00
-
-
Save ErickWendel/7ee9b41e94687d6af98712babe8a56dd to your computer and use it in GitHub Desktop.
Example of how to get video views from youtube
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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