GoogleAPI利用で詰まったところ(Ruby & YouTube Data API v3)～ターミナル上で動かすまで



Railsのアプリでyoutubeの動画を自動で貼り付けたくて、導入しようとしたけど、あるところで詰まったのでメモとして残しておく。

###まずは、Google API Keyを取得すること。
↓この記事を参考にしました。
https://www.plusdesign.co.jp/blog/?p=7752

youtubeの一般情報取得だけなら、OAuth2.0は登録しなくていいっぽい。

### 処理を書く。

とりあえずターミナル上で動くことを確認しました。

下記GemFileを作成し、bundle install。

```ruby:Gemfile
# frozen_string_literal: true

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem 'google-api-client', '<0.9'
# gem "rails"
gem 'optimist'
```

```ruby:youtube.rb
require 'rubygems'
require 'google/api_client'
require 'optimist'

# Set DEVELOPER_KEY to the API key value from the APIs & auth > Credentials
# tab of
# Google Developers Console <https://console.developers.google.com/>
# Please ensure that you have enabled the YouTube Data API for your project.
DEVELOPER_KEY = ' 取得したAPIKEYを書くこと'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'

def get_service
  client = Google::APIClient.new(
    :key => DEVELOPER_KEY,
    :authorization => nil,
    :application_name => $PROGRAM_NAME,
    :application_version => '1.0.0'
  )
  youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)

  return client, youtube
end

def main
  opts = Optimist::options do
    opt :q, 'Search term', :type => String, :default => '検索したい文字列'
    opt :max_results, 'Max results', :type => :int, :default => 25
  end

  client, youtube = get_service

  begin
    # Call the search.list method to retrieve results matching the specified
    # query term.
    search_response = client.execute!(
      :api_method => youtube.search.list,
      :parameters => {
        :part => 'snippet',
        :q => opts[:q],
        :maxResults => opts[:max_results]
      }
    )

    videos = []
    channels = []
    playlists = []

    # Add each result to the appropriate list, and then display the lists of
    # matching videos, channels, and playlists.
    search_response.data.items.each do |search_result|
      case search_result.id.kind
        when 'youtube#video'
          videos << "#{search_result.snippet.title} (#{search_result.id.videoId})"
        when 'youtube#channel'
          channels << "#{search_result.snippet.title} (#{search_result.id.channelId})"
        when 'youtube#playlist'
          playlists << "#{search_result.snippet.title} (#{search_result.id.playlistId})"
      end
    end

    puts "Videos:\n", videos, "\n"
    puts "Channels:\n", channels, "\n"
    puts "Playlists:\n", playlists, "\n"
  rescue Google::APIClient::TransmissionError => e
    puts "error!!!"
    puts e.result.body
  end
end

main
```

ターミナル上で```ruby youtube.rb```したら以下エラーが！

```
/.rbenv/versions/2.5.3/lib/ruby/2.5.0/net/
http/header.rb:23:in `block in initialize_http_header': 
header field value cannot include CR/LF (ArgumentError)
```

よくわからないけど、Rubyのバージョン2.5.3がうまくいかない原因みたいだった。

そこで2.4.1にバージョンを切り替えてもう一度```ruby youtube.rb```
そうするとまたエラーが！

```
{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "ipRefererBlocked",
    "message": "The request did not specify any referer. Please ensure that the client is sending referer or use the API Console to remove the referer restrictions.",    "extendedHelp": 
   }
  ],
  "code": 403,
  "message": "The request did not specify any referer. Please ensure that the client is sending referer or use the API Console to remove the referer restrictions."
 }
}
```

これの原因は、APIKeyの制限をGoogleCloudPlatform上でHTTPリファラーを設定したのがダメだったみたい。
なのでHTTPリファラーの制限をなしにしました。(APIキーの設定を変更した後は、キーの再生成をすること！)←ここで詰まった。

うまくいった！

```
Videos:
Earth, Wind &amp; Fire - September (Official Music Video) (Gs069dndIYk)
Earth, Wind &amp; Fire - Let&#39;s Groove (Official Music Video) (Lrle0x_DHBM)
Earth, Wind &amp; Fire - Boogie Wonderland (Official Music Video) (god7hAPv8f0)
Earth, Wind &amp; Fire - Fantasy (Audio) (r58GQYFZeLE)
Earth, Wind &amp; Fire - Fantasy (Official Music Video) (L0CVoFsUhC4)
The Best Of Earth Wind &amp; Fire (SocjITU2aPo)
Earth, Wind &amp; Fire - Reasons (Official Music Video) (0Qz_b1di3i8)
Earth, Wind &amp; Fire - In the stone, Settember, After the love has gone (mfagqCcyE6g)
Earth Wind &amp; Fire - Greatest Hits Live  (Full Album) (-qehsJRbwZ0)
Earth, Wind &amp; Fire - After The Love Has Gone (Live) (7tuJfud4W6U)
Earth, Wind &amp; Fire - Greatest Hits (1998)(full album) (0oGxgwehl2c)
Earth, Wind &amp; Fire - In the Stone (Audio) (6Z2xClustQo)
Earth, Wind &amp; Fire (3/16) - Lets groove (IcuWyMzdlnM)
Earth, Wind &amp; Fire (7/16) - Reason. (X_XNUMfQyMY)
AFTER THE LOVE HAS GONE - Earth, Wind and Fire Lyrics (yw-em78BCRw)
Earth, Wind &amp; Fire (8/11) - Thats the way of the world (_R2RsP43rmg)
Earth, Wind &amp; Fire - &quot;Lets Groove&quot; | Phil Wright Choreography | Ig : @phil_wright_ (_zdv23bAINM)
Earth, Wind &amp; Fire - After The Love Has Gone (Audio) (CUCLNPOjPZw)
Chicago and Earth, Wind &amp; Fire - Live at the Greek Theatre &#39;04_1СD (XzFPG4UtVko)
Earth Wind And Fire - Would You Mind (bvRlgDnbh_Q)
Earth, Wind &amp; Fire - September (Live) (Rm_9mxZV10U)
Earth, Wind and Fire - &quot;That&#39;s The Way of The World&quot; (5vIIZydXDqg)

Channels:
Earth Wind & Fire (UCztiH7D-fHwsMyUF8r15vsQ)
EarthWindandFireVEVO (UC72IXi6wx33LdltVkdwtLpw)

Playlists:
Best Of EARTH WIND AND FIRE (Playlist) (PLF9Dx60oSplx5RxRUHcuZNnVKszR4ZL6O)
```

とりあえずここまで、、、