Ruby 快速入門導覽課程

完成本頁其餘部分所述的步驟,大約五分鐘後,您就能建立簡單的 Ruby 指令列應用程式,向 YouTube Data API 發出要求。

本指南使用的程式碼範例會擷取 GoogleDevelopers YouTube 頻道的 channel 資源,並列印該資源的部分基本資訊。

必要條件

如要執行本快速入門導覽課程,您需要:

  • Ruby 2.0 以上版本。
  • 連上網際網路並使用網路瀏覽器。
  • Google 帳戶。

步驟 1:開啟 YouTube Data API

  1. 使用這個精靈在 Google Developers Console 中建立或選取專案,並自動開啟 API。依序點選「繼續」和「前往憑證」。

  2. 在「建立憑證」頁面,按一下「取消」按鈕。

  3. 選取頁面頂端的「OAuth 同意畫面」分頁標籤。 選取「Email address」(電子郵件地址),輸入「Product name」(產品名稱) (如尚未設定),然後按一下「Save」(儲存) 按鈕。

  4. 選取「憑證」分頁標籤,按一下「建立憑證」按鈕,然後選取「OAuth 用戶端 ID」。

  5. 選取應用程式類型「其他」,輸入名稱「YouTube Data API 快速入門導覽課程」,然後按一下「建立」按鈕。

  6. 按一下「確定」關閉隨即顯示的對話方塊。

  7. 按一下用戶端 ID 右側的「下載 JSON」按鈕。

  8. 將下載的檔案移到目前使用的目錄,並重新命名為 client_secret.json。

步驟 2:安裝 Google 用戶端程式庫

執行下列指令來安裝程式庫:

gem install google-api-client

如需其他安裝選項,請參閱程式庫的安裝頁面。

步驟 3:設定範例

在工作目錄中建立名為 quickstart.rb 的檔案,然後複製下列程式碼:

# Sample Ruby code for user authorization

require 'rubygems'
gem 'google-api-client', '>0.7'
require 'google/apis'
require 'google/apis/youtube_v3'
require 'googleauth'
require 'googleauth/stores/file_token_store'

require 'fileutils'
require 'json'

# REPLACE WITH VALID REDIRECT_URI FOR YOUR CLIENT
REDIRECT_URI = 'http://localhost'
APPLICATION_NAME = 'YouTube Data API Ruby Tests'

# REPLACE WITH NAME/LOCATION OF YOUR client_secrets.json FILE
CLIENT_SECRETS_PATH = 'client_secret.json'

# REPLACE FINAL ARGUMENT WITH FILE WHERE CREDENTIALS WILL BE STORED
CREDENTIALS_PATH = File.join(Dir.home, '.credentials',
                             "youtube-quickstart-ruby-credentials.yaml")

# SCOPE FOR WHICH THIS SCRIPT REQUESTS AUTHORIZATION
SCOPE = Google::Apis::YoutubeV3::AUTH_YOUTUBE_READONLY

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: REDIRECT_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: REDIRECT_URI)
  end
  credentials
end

# Initialize the API
service = Google::Apis::YoutubeV3::YouTubeService.new
service.client_options.application_name = APPLICATION_NAME
service.authorization = authorize

# Sample ruby code for channels.list

def channels_list_by_username(service, part, **params)
  response = service.list_channels(part, params).to_json
  item = JSON.parse(response).fetch("items")[0]

  puts ("This channel's ID is #{item.fetch("id")}. " +
        "Its title is '#{item.fetch("snippet").fetch("title")}', and it has " +
        "#{item.fetch("statistics").fetch("viewCount")} views.")
end

channels_list_by_username(service, 'snippet,contentDetails,statistics', for_username: 'GoogleDevelopers')

步驟 4:執行範例

使用下列指令執行範例:

ruby quickstart.rb

首次執行範例時,系統會提示您授予存取權:

  1. 範例會嘗試在預設瀏覽器中開啟新視窗或分頁。如果失敗,請從控制台複製網址,然後在瀏覽器中手動開啟。

    如果尚未登入 Google 帳戶,系統會提示您登入。如果您登入多個 Google 帳戶,系統會要求您選取要用於授權的帳戶。

  2. 按一下「接受」按鈕。
  3. 複製系統提供的程式碼,貼到指令列提示中,然後按下 Enter 鍵。授權後,重新導向的頁面網址可能會顯示授權碼:

    http://localhost/?code=4/nr_1TspmmQPFyifh7nz...OFo#

附註

  • 授權資訊會儲存在檔案系統中,因此後續執行作業時不會再提示授權。
  • 本範例中的授權流程適用於指令列應用程式。如要瞭解如何在網路應用程式中執行授權,請參閱「將 OAuth 2.0 用於網路伺服器應用程式」。

延伸閱讀