Ruby 快速入門導覽課程

完成本頁其餘步驟,您將在大約五分鐘內取得一個簡單的 Ruby 指令列應用程式,向 YouTube Data API 發出要求。

本指南中使用的程式碼範例會擷取 Google 開發人員 YouTube 頻道的 channel 資源,並列印該資源中的一些基本資訊。

必要條件

如要執行本快速入門導覽課程,您必須符合以下條件:

  • Ruby 2.0 以上版本。
  • 網際網路和網路瀏覽器存取。
  • Google 帳戶。

步驟 1:啟用 YouTube Data API

  1. 請使用這個精靈在 Google Developers Console 中建立或選取專案,並自動啟用這個 API。按一下 [繼續],然後點選 [前往憑證]

  2. 在「Create credentials」(建立憑證) 頁面中,按一下 [Cancel] (取消) 按鈕。

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

  4. 選取 [憑證] 分頁標籤,按一下 [建立憑證] 按鈕並選取 [OAuth 用戶端 ID]

  5. 選取「Other」(其他) 應用程式類型,輸入「YouTube Data API 快速入門」名稱,然後按一下 [Create] (建立) 按鈕。

  6. 按一下「OK」,關閉產生的對話方塊。

  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#

Notes

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

延伸閱讀