11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby で YouTube Data API (v3) を使う

Last updated at Posted at 2016-09-24

Google の YouTube Data API (v3) をRubyから使ってみました。

APIのアクセスにはGoogleのgoogle-api-ruby-clientを使いました。 google-api-ruby-clientのバージョンは0.9.15を使いました。

google-api-ruby-clientが0.9からAPI仕様が変更になったので、以前のコードが動かなくなったので、サンプルコードを探す場合は注意してください。

google-api-clientをインストール

gem install google-api-client

認証情報を用意する。

RubyでYouTube Data APIを利用したときのメモ」を参考にOAuthの認証用のjsonを作成して、カレントディレクトリのclient_secret.jsonに保存してください。

videoの統計情報を取得

videoのidを指定して、videoの統計情報を取得する例です。

require 'googleauth'
require 'googleauth/stores/file_token_store'
require 'google/apis/youtube_v3'

OOB_URI = 'urn:ietf:wg:oauth:2.0:oob'
APPLICATION_NAME = 'idolsongplaylist'
CLIENT_SECRETS_PATH = 'client_secret.json'
CREDENTIALS_PATH = File.join(Dir.home, '.credentials', "tokens.yaml")
SCOPE = [ "https://www.googleapis.com/auth/youtube" ]

def authorize
  FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))

  client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
  token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)
  authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)
  user_id = 'default'
  credentials = authorizer.get_credentials(user_id)
  if credentials.nil?
    url = authorizer.get_authorization_url(base_url: OOB_URI)
    puts 'Open the following URL in the browser and enter the ' +
         'resulting code after authorization'
    puts url
    code = gets
    credentials = authorizer.get_and_store_credentials_from_code(
      user_id: user_id, code: code, base_url: OOB_URI)
  end
  credentials
end

YT = Google::Apis::YoutubeV3
youtube = YT::YouTubeService.new
youtube.client_options.application_name = APPLICATION_NAME
youtube.authorization = authorize

options = {
  :id => 'xftKTwxb5oE'
}

response = youtube.list_videos("statistics", options)
pp response

最初の実行時に、OAuthのURLがブラウザでアクセスしてtokenを入手して、コンソールに入力します。tokenはファイルに保存します。

実行結果

$ ruby youtube.rb 
#<Google::Apis::YoutubeV3::ListVideosResponse:0x00000002a16830
 @etag="\"I_8xdZu766_FSaexEaDXTIfEWc0/UgLSmvYEE1Uf_wWAE2v8aEtIzGo\"",
 @items=
  [#<Google::Apis::YoutubeV3::Video:0x00000002a14b70
    @etag="\"I_8xdZu766_FSaexEaDXTIfEWc0/b2sFHVQhw1hpCcYfRa2TtA0Ef94\"",
    @id="xftKTwxb5oE",
    @kind="youtube#video",
    @statistics=
     #<Google::Apis::YoutubeV3::VideoStatistics:0x00000002a19648
      @comment_count="0",
      @dislike_count="0",
      @favorite_count="0",
      @like_count="0",
      @view_count="14">>],
 @kind="youtube#videoListResponse",
 @page_info=
  #<Google::Apis::YoutubeV3::PageInfo:0x00000002a1ea80
   @results_per_page=1,
   @total_results=1>>

view_countで再生回数が取得できています。

再生リストの概要を取得

上記のコードから変更した部分のみです。

optinons = {
  :id => 'PL0FtIyL-iyaOO_hxe07XsH4DKYiAJS_AP'
}
response = youtube.list_playlists("snippet", optinons)
pp response 

実行結果

$ ruby playlist.rb
#<Google::Apis::YoutubeV3::ListPlaylistResponse:0x000000032ecae0
 @etag="\"I_8xdZu766_FSaexEaDXTIfEWc0/wQGgUcbPqkYP06aXjsi0EyjUwTQ\"",
 @items=
  [#<Google::Apis::YoutubeV3::Playlist:0x000000032f23f0
    @etag="\"I_8xdZu766_FSaexEaDXTIfEWc0/4mg4-WLMwCQBTCAkrzW7f2jvlNk\"",
    @id="PL0FtIyL-iyaOO_hxe07XsH4DKYiAJS_AP",
    @kind="youtube#playlist",
    @snippet=
     #<Google::Apis::YoutubeV3::PlaylistSnippet:0x000000032f05f0
      @channel_id="UCIW5K2iQsZn6dz0yLNlT1Nw",
      @channel_title="eggmansan",
      @description=
       "2016年に公開されたアイドルの曲の動画を集めてみました。\n\nレギュレーション(なるべく)\n・公式の動画\n ・1曲単位の動画",
      @localized=
       #<Google::Apis::YoutubeV3::PlaylistLocalization:0x000000032f6a40
        @description=
         "2016年に公開されたアイドルの曲の動画を集めてみました。\n\nレギュレーション(なるべく)\n・公式の動画\n・1曲単位の動画",
        @title="アイドルの曲2016">,
      @published_at=
       #<DateTime: 2016-09-18T12:28:19+00:00 ((2457650j,44899s,0n),+0s,2299161j)>,
      @thumbnails=
       #<Google::Apis::YoutubeV3::ThumbnailDetails:0x000000032f9358
        @default=
         #<Google::Apis::YoutubeV3::Thumbnail:0x000000032f87c8
          @height=90,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/default.jpg",
          @width=120>,
        @high=
         #<Google::Apis::YoutubeV3::Thumbnail:0x000000032ff140
          @height=360,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/hqdefault.jpg",
          @width=480>,
        @maxres=
         #<Google::Apis::YoutubeV3::Thumbnail:0x000000032fdb88
          @height=720,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/maxresdefault.jpg",
          @width=1280>,
        @medium=
         #<Google::Apis::YoutubeV3::Thumbnail:0x000000032fc5d0
          @height=180,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/mqdefault.jpg",
          @width=320>,
        @standard=
         #<Google::Apis::YoutubeV3::Thumbnail:0x00000003302fc0
          @height=480,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/sddefault.jpg",
          @width=640>>,
      @title="アイドルの曲2016">>],
 @kind="youtube#playlistListResponse",
 @page_info=
  #<Google::Apis::YoutubeV3::PageInfo:0x00000003300b58
   @results_per_page=5,
   @total_results=1>>

再生リストのアイテムを取得

上記のコードから変更した部分のみです。

optinons = {
  :playlist_id => 'PL0FtIyL-iyaOO_hxe07XsH4DKYiAJS_AP',
  :max_results => 2
}
response = youtube.list_playlist_items("snippet", optinons)
pp response 

実行結果

$ ruby playlist.rb
#<Google::Apis::YoutubeV3::ListPlaylistItemsResponse:0x0000000350d1a8
 @etag="\"I_8xdZu766_FSaexEaDXTIfEWc0/Ut4NhrCJxTetxWrI6D0nilNL6lY\"",
 @items=
  [#<Google::Apis::YoutubeV3::PlaylistItem:0x00000003511ac8
    @etag="\"I_8xdZu766_FSaexEaDXTIfEWc0/wIUGE87XjC983shu9wpKdjunJ9E\"",
    @id="UEwwRnRJeUwtaXlhT09faHhlMDdYc0g0REtZaUFKU19BUC45ODY0RDA1N0ZBMkE1M0E1",
    @kind="youtube#playlistItem",
    @snippet=
     #<Google::Apis::YoutubeV3::PlaylistItemSnippet:0x00000003510218
      @channel_id="UCIW5K2iQsZn6dz0yLNlT1Nw",
      @channel_title="eggmansan",
      @description="このビデオの情報サハ゛ーイ夏MV",
      @playlist_id="PL0FtIyL-iyaOO_hxe07XsH4DKYiAJS_AP",
      @position=0,
      @published_at=
       #<DateTime: 2016-09-25T00:32:05+00:00 ((2457657j,1925s,0n),+0s,2299161j)>,
      @resource_id=
       #<Google::Apis::YoutubeV3::ResourceId:0x00000003519d68
        @kind="youtube#video",
        @video_id="PS1jTwuXI0Y">,
      @thumbnails=
       #<Google::Apis::YoutubeV3::ThumbnailDetails:0x000000035186c0
        @default=
         #<Google::Apis::YoutubeV3::Thumbnail:0x0000000351fad8
          @height=90,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/default.jpg",
          @width=120>,
        @high=
         #<Google::Apis::YoutubeV3::Thumbnail:0x0000000351e4d0
          @height=360,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/hqdefault.jpg",
          @width=480>,
        @maxres=
         #<Google::Apis::YoutubeV3::Thumbnail:0x0000000351cf18
          @height=720,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/maxresdefault.jpg",
          @width=1280>,
        @medium=
         #<Google::Apis::YoutubeV3::Thumbnail:0x000000035238e0
          @height=180,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/mqdefault.jpg",
          @width=320>,
        @standard=
         #<Google::Apis::YoutubeV3::Thumbnail:0x00000003522328
          @height=480,
          @url="https://i.ytimg.com/vi/PS1jTwuXI0Y/sddefault.jpg",
          @width=640>>,
      @title="????夏!!!BANG!BANG!BANG!!!">>,
   #<Google::Apis::YoutubeV3::PlaylistItem:0x00000003520730
    @etag="\"I_8xdZu766_FSaexEaDXTIfEWc0/oUHNLvMf4PX8UqpCBcJ0iU5d_LQ\"",
    @id="UEwwRnRJeUwtaXlhT09faHhlMDdYc0g0REtZaUFKU19BUC43OEFDM0Q4REIzREZBNEY4",
    @kind="youtube#playlistItem",
    @snippet=
     #<Google::Apis::YoutubeV3::PlaylistItemSnippet:0x00000003526ea0
      @channel_id="UCIW5K2iQsZn6dz0yLNlT1Nw",
      @channel_title="eggmansan",
      @description=
       "動画の説明 長いので省略",
      @playlist_id="PL0FtIyL-iyaOO_hxe07XsH4DKYiAJS_AP",
      @position=1,
      @published_at=
       #<DateTime: 2016-09-24T02:46:35+00:00 ((2457656j,9995s,0n),+0s,2299161j)>,
      @resource_id=
       #<Google::Apis::YoutubeV3::ResourceId:0x000000035246f0
        @kind="youtube#video",
        @video_id="YAOK5wEpAX8">,
      @thumbnails=
       #<Google::Apis::YoutubeV3::ThumbnailDetails:0x0000000352aff0
        @default=
         #<Google::Apis::YoutubeV3::Thumbnail:0x0000000352a500
          @height=90,
          @url="https://i.ytimg.com/vi/YAOK5wEpAX8/default.jpg",
          @width=120>,
        @high=
         #<Google::Apis::YoutubeV3::Thumbnail:0x00000003528f48
          @height=360,
          @url="https://i.ytimg.com/vi/YAOK5wEpAX8/hqdefault.jpg",
          @width=480>,
        @maxres=
         #<Google::Apis::YoutubeV3::Thumbnail:0x0000000352f910
          @height=720,
          @url="https://i.ytimg.com/vi/YAOK5wEpAX8/maxresdefault.jpg",
          @width=1280>,
        @medium=
         #<Google::Apis::YoutubeV3::Thumbnail:0x0000000352e358
          @height=180,
          @url="https://i.ytimg.com/vi/YAOK5wEpAX8/mqdefault.jpg",
          @width=320>,
        @standard=
         #<Google::Apis::YoutubeV3::Thumbnail:0x0000000352cda0
          @height=480,
          @url="https://i.ytimg.com/vi/YAOK5wEpAX8/sddefault.jpg",
          @width=640>>,
      @title="CHERRSEE 「白いシャツ」 Music Video Dance ver.">>],
 @kind="youtube#playlistItemListResponse",
 @next_page_token="CAIQAA",
 @page_info=
  #<Google::Apis::YoutubeV3::PageInfo:0x00000003532728
   @results_per_page=2,
   @total_results=1320>>```

参考

参考にしたコード

あとで追記
google-api-ruby-clientのリポジトリにもサンプルがあった
* https://github.com/google/google-api-ruby-client/blob/master/samples/cli/lib/samples/you_tube.rb

参考にしたページ

11
9
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
11
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?