LoginSignup
37
43

More than 3 years have passed since last update.

Railsでyoutube APIを使ってみた

Posted at

はじめに

あまりにもわからなかったので、出来たことをまとめてみました。

参考↓
さかな前線(YouTube Data API V3とgoogle-api-ruby-client gemでYouTube動画検索)
Class: Google::Apis::YoutubeV3::YouTubeService-github
YouTube Data API (v3)

プロジェクトを作成(YouTube Data API v3を使う)

以下のサイトの通りにやれば、いいです。↓
YouTube Data API (v3)

まず、Rubyで試してみる

このサイトを真似してます。↓
さかな前線(YouTube Data API V3とgoogle-api-ruby-client gemでYouTube動画検索)

手元のRuby環境にGemをインストールします。

$ gem install google-api-client -v 0.9.20
ruby.rb
require 'google/apis/youtube_v3'
require 'active_support/all'

GOOGLE_API_KEY="<API_KEY>" #上記で作成したキー

def find_videos(keyword, after: 1.months.ago, before: Time.now) #検索キーワードと検索範囲を変えれるように引数に値を取っています
  service = Google::Apis::YoutubeV3::YouTubeService.new
  service.key = GOOGLE_API_KEY
  next_page_token = nil
  opt = {
    q: keyword,
    type: 'video',
    max_results: 2,
    order: :date,
    page_token: next_page_token,
    published_after: after.iso8601,
    published_before: before.iso8601
  }
  results = service.list_searches(:snippet, opt)
  results.items.each do |item|
    id = item.id
    snippet = item.snippet
    puts "\"#{snippet.title}\" by #{snippet.channel_title} (id: #{id.video_id}) (#{snippet.published_at})"
  end
end

find_videos('明日香ちゃんねる')

出力結果↓

"私は盛大に騙されました。" by 明日香ちゃんねる (id: ViYzZFSTMoM) (2019-07-31T14:19:27+00:00)
"【明日香VS現役東大生】東大生のスキを突いてゴールを狙う!!!" by 明日香ちゃんねる (id: -HzWQzHNvPs) (2019-07-30T08:58:45+00:00)

ちゃんと2件とれました。

list_searches

list_searchesメソッドは以下のサイトに説明が載っています。
list_searchesメソッド以外にもlist_channelsとか様々なメソッドがあるみたいです。↓(optについてもここを参考)
Class: Google::Apis::YoutubeV3::YouTubeService-github

iso8601

published_afterはRFC 3339形式の日時の値を入れる必要があるみたいです。
to_datetime.rfc3339iso8601メソッドで変換します。
参考↓
RubyでTimeクラスオブジェクトをRFC3339に変換する
RubyのTime型のオブジェクトをiso8601形式の文字列に変換する

試してみた↓

ruby1.rb
require 'date'
require 'time'

puts Time.now
puts Time.now.to_datetime.rfc3339
puts Time.now.iso8601

出力結果↓

2019-08-01 12:42:33 +0900
2019-08-01T12:42:33+09:00
2019-08-01T12:42:33+09:00

YouTube Data API v3のQueriesについて(無料枠)

一日当たり、10,000Queriesでそれ以上超えると通信が出来なくなりエラーになってしまいます。
なので、一回のリクエストで50件も取ってしまうとすぐ10,000Queries超えてエラーになりますので注意!!
ダッシュボードから確認出来ます。
参考↓
【メモ】Youtube API Data (v3)のクオータについて-Qiita

Ruby on Railsで試してみる

gemのバージョンによってrequire: 'google/apis/youtube_v3'が読み取れないようなので、
固定してます。何回もエラーが出て苦しめられたので...

gemfile
gem 'google-api-client', '0.9.20', require: 'google/apis/youtube_v3'

youtubeコントローラーを作ってユーチュブからデータを取得するfind_videosとビューに表示するindexに分けています。

youtube_controller.rb
class YoutubeController < ApplicationController
  GOOGLE_API_KEY = Rails.application.credentials.google[:api_key]

  def find_videos(keyword, after: 1.months.ago, before: Time.now)
    service = Google::Apis::YoutubeV3::YouTubeService.new
    service.key = GOOGLE_API_KEY

    next_page_token = nil
    opt = {
      q: keyword,
      type: 'video',
      max_results: 3,
      order: :date,
      page_token: next_page_token,
      published_after: after.iso8601,
      published_before: before.iso8601
    }
    service.list_searches(:snippet, opt)
  end

  def index
    @youtube_data = find_videos('明日香ちゃんねる')
  end
end
views/youtube/index.html.erb

<% @youtube_data.items.each do |item| %>
  <% snippet = item.snippet %>
  <p><%= snippet.title %></p>
  <p><%= snippet.published_at %><%= snippet.channel_title %></p>
  <div><iframe width="560" height="315" src="https://www.youtube.com/embed/<%= item.id.video_id %>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
<% end %>

iframeのyoutubeのurlに取得したvideo_idを入れてます。
キーワードにマッチする動画3件を取得できました。
完成しサイトです↓
sample_image.png

最後に

他のgemでytというのを見つけたのでリンクを貼っておきます。こっちのほうがわかりやすそう😅
yt-gem
Yt · The reliable YouTube API Ruby client

37
43
5

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
37
43