Purus
Purus

Reputation: 5819

Youtube V3 API - Fetch a random video based on keyword

I am using the below code to navigate to different pages of Youtube data.

I call the service again and again based on $randomNumber ( 1 to 20). But I don't think this is the better way.

 $youtube = new Google_Service_YouTube($client);

    $searchResponse = $youtube->search->listSearch('id,snippet', array(
        'type' => 'video',
        'q' => $searchTerm,
        'maxResults' => $videoCount
    ));

    $nextPage = $searchResponse["nextPageToken"];

    for($i=1;$i< $randomNumber ;$i++){

        $newSearchResponse = $youtube->search->listSearch('id,snippet', array(
            'q' => $searchTerm,
            'maxResults' => $videoCount,
            'type' => "video",
            'pageToken' => $nextPage
        ));

        $nextPage = $newSearchResponse["nextPageToken"];

    }

   return $newSearchResponse;

Please let me know how to get a random video based on the search text.

Upvotes: 2

Views: 1928

Answers (1)

Pierfrancesco Soffritti
Pierfrancesco Soffritti

Reputation: 1738

Unfortunately there's no official way to get random videos with YouTube Data API.
Take a look at this question: How do I get a random YouTube video with the YouTube API?

I had a similar need, and i've "solved it" in a similar way to you: i made a few search->list requests to the API, with maxResults set to 50, (while keeping track of the video IDs) and then picked a random video from the resulting set.

This is not random at all, but I don't see any other way around the problem without having far too complex solutions.

Upvotes: 3

Related Questions