APIの作成
- APIコンソールにログイン(https://console.developers.google.com/?hl=ja)
- プロジェクトを作成
- サイドバー「認証情報」から「認証情報を作成」「APIキー」を選択しAPIキーを作成
- APIキーをコピー(後でプログラムに使用します)
- 「ダッシュボード」「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