DEV Community

wimdenherder
wimdenherder

Posted on

Fetch youtube api for free (in dev console)

You have to be on the youtube.com website, open the dev console, and then you can actually find results from the youtube api for free:

async function fetchYtInitialData(url) {
  let pageHtml = await (await fetch(url)).text(), result;
  try { return JSON.parse(pageHtml.split('var ytInitialData = ')[1].split(';</script>')[0]); } catch(err) { console.error(err) }
}

async function freeYoutubeApiCall(query) {
  ytInitialData = await fetchYtInitialData('https://www.youtube.com/results?search_query=' + query);
  const videoData = [];
  ytInitialData.contents.twoColumnSearchResultsRenderer.primaryContents.sectionListRenderer.contents.forEach(y => y.itemSectionRenderer?.contents.forEach(x => { 
      if(x.videoRenderer) videoData.push(x.videoRenderer);
    })
  );
  return videoData;
}

let results = await freeYoutubeApiCall('rick roll');
results;
results.map(x => x.videoId);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)