LoginSignup
4
5

More than 3 years have passed since last update.

RubyでYouTube検索を実装するAPIを使ってみた

Last updated at Posted at 2019-09-20

APIの作成

  1. APIコンソールにログイン(https://console.developers.google.com/?hl=ja)
  2. プロジェクトを作成
  3. サイドバー「認証情報」から「認証情報を作成」「APIキー」を選択しAPIキーを作成
  4. APIキーをコピー(後でプログラムに使用します)
  5. 「ダッシュボード」「APIの有効化」から「YouTube Data API v3」を選択

RubyからAPIを利用

Gemのインストール

gem install google-api-client

Gemfileに記述する場合

gem 'google-api-client'

APIの初期化

require 'google/apis/youtube_v3'

# 動画データを取得できるオブジェクトを作成
youtube = Google::Apis::YoutubeV3::YouTubeService.new
# 先ほど作成したAPIキーを入力
youtube.key = "APIキー"

動画データの検索

require 'google/apis/youtube_v3'

youtube = Google::Apis::YoutubeV3::YouTubeService.new
youtube.key = "APIキー"

youtube_search_list = youtube.list_searches("id,snippet", type: "video", q: "久保", max_results: 50)

タイトルとURLを抽出

require 'google/apis/youtube_v3'

youtube = Google::Apis::YoutubeV3::YouTubeService.new
youtube.key = "APIキー"

youtube_search_list = youtube.list_searches("id,snippet", type: "video", q: "久保", max_results: 50)

text = ""

youtube_search_list.items.each do |item|
  title = item.snippet.title
  video_id = item.id.video_id

  text +=<<~EOS

  タイトル:#{title}
  URL:https://www.youtube.com/watch?v=#{video_id}

  EOS
end

puts text
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5