Skip to content

Instantly share code, notes, and snippets.

@cecyc
Last active July 17, 2018 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecyc/3b6fb5038f8d598fe276a7214340c525 to your computer and use it in GitHub Desktop.
Save cecyc/3b6fb5038f8d598fe276a7214340c525 to your computer and use it in GitHub Desktop.
Simple script to request a video from YouTube API
// Request to YouTube
const API_KEY=""
const videoUrl = "https://www.youtube.com/watch?v="
let reqUrl = `https://www.googleapis.com/youtube/v3/search?key=API_KEY&part=snippet&q=${query}&maxResults=25`
//Get a random int to pick a random video from the results
const getRandomInt = () => {
let num = Math.random
//maxResults are 25 index 0, get a random number between 0 and 24
return Math.floor(num * 24)
}
//Get URL of cat videos from YouTube
const getUrl = () => {
let req = new XMLHttpRequest()
req.open("GET", reqUrl, true)
req.send()
req.onload = () => {
if (req.readyState === 4 && req.status === 200) {
let res = JSON.parse(req.responseText)
//want results to be random
let i = getRandomInt()
let videoId = res["items"][i]["id"]["videoId"]
let url = videoUrl + videoId
console.log(url)
return url
} else {
console.log("request got status: " + req.status + "error: " + req.statusText)
return defaultUrl
}
}
}
getUrl()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment