Readme

Get YT Video Information

Given a youtube video url, this val returns a small amount of information about the video: title, channel title, and the description. It uses the Youtube Data API v3, so you need to bring your own API key to get it to work (see here about setting up an API key).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=41";
export async function getVideoInfo(videoURL, key) {
const { default: axios } = await import("npm:axios");
if (!videoURL) {
console.error("No URL Provided");
return null;
}
if (!key) {
console.warn("API Key is Invalid");
return null;
}
const idRegex =
/^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
const videoId = videoURL.match(idRegex)?.[7];
if (videoId && videoId.length === 11) {
const requestUrl =
`https://www.googleapis.com/youtube/v3/videos?part=id%2Csnippet,statistics,contentDetails,status&id=${videoId}&key=${key}`;
const vidInfo = await fetchJSON(requestUrl).catch(
(error) => {
console.error("Error retrieving video information:", error);
return null;
},
);
const { title, channelTitle, description } = vidInfo.items[0].snippet;
return { title, channelTitle, description };
}
else {
console.log("The URL doesn't match with the expected format");
return null;
}
}
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023