0

I am trying to use the YouTube API to pull random video IDs into Google Sheets. I have very little experience with the YouTube API, with only having used it once before to pull search results.

I did some research and haven't found much for combining the API with Google Sheets, and I do not have enough knowledge about other languages to be able to translate into Google Apps Script.

I am currently using the example script from the developer page, with the search parameter removed (Original: var results = YouTube.Search.list('id,snippet', {q: 'dogs', maxResults: 25});).

function searchByKeyword() {
  var results = YouTube.Search.list('id,snippet', {maxResults: 25});

  for(var i in results.items) {
    var item = results.items[i];
    Logger.log('[%s] Title: %s', item.id.videoId, item.snippet.title);
  }
}

When I run this, it works fine and successfully pulls video titles and IDs, but the results are always the same.

I believe there are a couple things I am not understanding here, and could use some help on:

  1. How does this script work in terms of the results? (Where do the results come from)
  2. Is there a way to make the results random?

Just for clarification, I understand the structure of the code and what it does when it runs. I don't understand where the YouTube API is getting the results from.

In this post, I am not focusing on placing the data into a google sheet just yet, but if somebody knows how to I would definitely appreciate the help with that as well. I would just want the Title and ID to be in two separate cells in the same row. Specific cells do not matter right now.

kaitlynmm569
  • 1,605
  • 1
  • 6
  • 18
  • Welcome to the SO search: https://stackoverflow.com/search?q=youtube+api+random+video – Kos Aug 13 '20 at 14:02
  • @Kos I have looked through that. My problem is that I could not find anything specifically for Google App Script, and as I mentioned, I do not know any other languages well enough to be able to translate. – kaitlynmm569 Aug 13 '20 at 14:16
  • then [this](https://stackoverflow.com/a/11316247/555121) or [this](https://stackoverflow.com/a/32066224/555121) – Kos Aug 13 '20 at 18:30
  • @Kos I did my research. I already read both of those posts before posting my own question. Nothing i found gave me an answer i wanted. Thanks anyways. – kaitlynmm569 Aug 13 '20 at 20:54

1 Answers1

2

You may try sorting the search results by date (results are sorted in reverse chronological order) and each time you run the API, it will send you the most recent matching uploads which may be different from the last result set.

You can replace:

var results = YouTube.Search.list('id,snippet', {q: "dogs", maxResults: 25});

with

var results = YouTube.Search.list('id,snippet', {q: "dogs", maxResults: 25, order: "date", type: "video" });
Amit Agarwal
  • 10,910
  • 1
  • 32
  • 43