Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a random YouTube video with the YouTube API?

I need a way of getting a completely random YouTube video. No restriction.

How can I do with with the YouTube API?

** edit * OK as requested here is what i tried so far:

1 - went through the api and examples at youtube dev site. http://www.youtube.com/dev/ no luck finding the correct api or a way of doing it there.

2 - google search of course ;) got http://randomyoutubevideo.net/ but they only offer an api from THEM to use in between me and youtube. < this gives me hope that it IS actually possible to do this.

3 - even checked the youtube app gallery http://youtube-gallery.appspot.com/ to see if anyone is doing it. and HOW.

what i will also do is ask on the youtube discussion pages. perhaps someone there can help.

like image 469
b0x0rz Avatar asked Jul 03 '12 16:07

b0x0rz


1 Answers

Step 1: Create API-Key

  1. Create a google-Account
  2. Visit: https://console.developers.google.com/
  3. Create a new project: Click on Create new Project in head-menu and give it a name
  4. Now Activate the YoutTubeData API: Click it and enable it.
  5. Insert your Applications-Infos
  6. Click "create Credentials"
  7. Klick what do i need?
  8. Note your API-Key

Now you can access the YouTube-API.

Step 2: Use YouTube-API to crawl Videos

In this step we use the YouTube-API to get random VideoId's. With the following Code-Samples you will get 50 random Apis from the YouTube-Search. That's the maximum. You can store them in a DB or return a random ID directly.

Attention: There is a limit of 30,000 units/second/user and 1,000,000 per day.

Codesamples


[C#-Example]

using System;
using System.Linq;
using System.Net;
using Newtonsoft.Json;

namespace YouTube
{
   class Program
   {
    private static Random random = new Random();

    public static string RandomString(int length)
    {
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        return new string(Enumerable.Repeat(chars, length)
          .Select(s => s[random.Next(s.Length)]).ToArray());
    }

    static void Main(string[] args)
    {
        var count = 50;
        var API_KEY = "YOUR KEY";
        var q = RandomString(3);
        var url = "https://www.googleapis.com/youtube/v3/search?key=" + API_KEY + "&maxResults="+count+"&part=snippet&type=video&q=" +q;

        using (WebClient wc = new WebClient())
        {
            var json = wc.DownloadString(url);
            dynamic jsonObject = JsonConvert.DeserializeObject(json);
            foreach (var line in jsonObject["items"])
            {
                Console.WriteLine(line["id"]["videoId"]);
                /*store your id*/
            }
            Console.Read();
        }
    }
}
}

[PHP-Example]

function crawlVideos($count = 50)
{
    $q = $this->generateRandomString(3);
    $url = "https://www.googleapis.com/youtube/v3/search?key=" . self::API_KEY . "&maxResults=$count&part=snippet&type=video&q=" . $q;
    $JSON = file_get_contents($url);
    $JSON_Data_search = json_decode($JSON);
    foreach ($JSON_Data_search->{"items"} as $result) {
        $videoId = ($result->{"id"}->{"videoId"});
        /*Insert video to your database*/
    }
}

function generateRandomString($length = 10)
{
    return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

[Python-Example]

import json
import urllib.request
import string
import random

count = 50
API_KEY = 'your_key'
random = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(3))

urlData = "https://www.googleapis.com/youtube/v3/search?key={}&maxResults={}&part=snippet&type=video&q={}".format(API_KEY,count,random)
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
encoding = webURL.info().get_content_charset('utf-8')
results = json.loads(data.decode(encoding))

for data in results['items']:
    videoId = (data['id']['videoId'])
    print(videoId)
    #store your ids

Step 3: Generate/Return your Video-URL

Now read a random ID from database like:

SELECT 'id' 
FROM yttable
WHERE 1 ORDER BY RAND() LIMIT 1

Your random video is:

https://www.youtube.com/embed/[random ID]

Have fun!

like image 140
osanger Avatar answered Oct 26 '22 04:10

osanger