Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Hoàn tất các bước được mô tả trong phần còn lại của trang này và trong khoảng 5 phút, bạn sẽ có một ứng dụng dòng lệnh Ruby đơn giản để gửi yêu cầu đến YouTube Data API.
Mã mẫu được dùng trong hướng dẫn này sẽ truy xuất tài nguyên channel cho kênh GoogleDevelopers trên YouTube và in một số thông tin cơ bản từ tài nguyên đó.
Điều kiện tiên quyết
Để chạy hướng dẫn bắt đầu nhanh này, bạn cần có:
Ruby 2.0 trở lên.
Có quyền truy cập vào Internet và trình duyệt web.
Tài khoản Google.
Bước 1: Bật YouTube Data API
Sử dụng trình hướng dẫn này để tạo hoặc chọn một dự án trong Google Developers Console và tự động bật API. Nhấp vào Tiếp tục, rồi nhấp vào Chuyển đến phần thông tin đăng nhập.
Trên trang Tạo thông tin xác thực, hãy nhấp vào nút Huỷ.
Ở đầu trang, hãy chọn thẻ Màn hình xin phép bằng OAuth.
Chọn một Địa chỉ email, nhập Tên sản phẩm nếu chưa đặt và nhấp vào nút Lưu.
Chọn thẻ Thông tin xác thực, nhấp vào nút Tạo thông tin xác thực rồi chọn Mã ứng dụng OAuth.
Chọn loại ứng dụng Khác, nhập tên "YouTube Data API Quickstart" rồi nhấp vào nút Tạo.
Nhấp vào OK để đóng hộp thoại kết quả.
Nhấp vào nút file_download (Tải JSON xuống) ở bên phải mã nhận dạng ứng dụng.
Di chuyển tệp đã tải xuống vào thư mục đang hoạt động rồi đổi tên thành client_secret.json.
Bước 2: Cài đặt Thư viện ứng dụng Google
Chạy lệnh sau để cài đặt thư viện:
gem install google-api-client
Hãy xem trang cài đặt của thư viện để biết các lựa chọn cài đặt thay thế.
Bước 3: Thiết lập mẫu
Tạo một tệp có tên là quickstart.rb trong thư mục làm việc rồi sao chép đoạn mã sau vào:
# Sample Ruby code for user authorizationrequire'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 CLIENTREDIRECT_URI='http://localhost'APPLICATION_NAME='YouTube Data API Ruby Tests'# REPLACE WITH NAME/LOCATION OF YOUR client_secrets.json FILECLIENT_SECRETS_PATH='client_secret.json'# REPLACE FINAL ARGUMENT WITH FILE WHERE CREDENTIALS WILL BE STOREDCREDENTIALS_PATH=File.join(Dir.home,'.credentials',"youtube-quickstart-ruby-credentials.yaml")# SCOPE FOR WHICH THIS SCRIPT REQUESTS AUTHORIZATIONSCOPE=Google::Apis::YoutubeV3::AUTH_YOUTUBE_READONLYdefauthorizeFileUtils.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)ifcredentials.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"putsurlcode=getscredentials=authorizer.get_and_store_credentials_from_code(user_id:user_id,code:code,base_url:REDIRECT_URI)endcredentialsend# Initialize the APIservice=Google::Apis::YoutubeV3::YouTubeService.newservice.client_options.application_name=APPLICATION_NAMEservice.authorization=authorize# Sample ruby code for channels.listdefchannels_list_by_username(service,part,**params)response=service.list_channels(part,params).to_jsonitem=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.")endchannels_list_by_username(service,'snippet,contentDetails,statistics',for_username:'GoogleDevelopers')
Trong lần đầu tiên bạn chạy mẫu, mẫu này sẽ nhắc bạn uỷ quyền truy cập:
Mẫu này cố gắng mở một cửa sổ hoặc thẻ mới trong trình duyệt mặc định của bạn.
Nếu cách này không hiệu quả, hãy sao chép URL từ bảng điều khiển rồi mở URL đó theo cách thủ công trong trình duyệt.
Nếu chưa đăng nhập vào Tài khoản Google, bạn sẽ được nhắc đăng nhập. Nếu đã đăng nhập vào nhiều Tài khoản Google, bạn sẽ được yêu cầu chọn một tài khoản để dùng cho việc uỷ quyền.
Nhấp vào nút Chấp nhận.
Sao chép mã bạn nhận được, dán mã đó vào dấu nhắc dòng lệnh rồi nhấn phím Enter. Mã này có thể xuất hiện trong URL của trang mà bạn được chuyển hướng đến sau khi cấp quyền uỷ quyền:
Thông tin uỷ quyền được lưu trữ trên hệ thống tệp, vì vậy, các lần thực thi tiếp theo sẽ không nhắc bạn uỷ quyền.
Quy trình uỷ quyền trong ví dụ này được thiết kế cho một ứng dụng dòng lệnh. Để biết thông tin về cách thực hiện uỷ quyền trong một ứng dụng web, hãy xem bài viết Sử dụng OAuth 2.0 cho ứng dụng máy chủ web.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-21 UTC."],[[["\u003cp\u003eThis guide walks you through creating a simple Ruby command-line application that interacts with the YouTube Data API in approximately five minutes.\u003c/p\u003e\n"],["\u003cp\u003eThe application retrieves and displays basic information about the GoogleDevelopers YouTube channel using the YouTube Data API.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves enabling the YouTube Data API, installing the Google Client Library for Ruby, and setting up and running the provided sample code \u003ccode\u003equickstart.rb\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe first time you run the application, you'll be prompted to authorize access to your Google account, which will be saved for future executions.\u003c/p\u003e\n"],["\u003cp\u003eThe sample code showcases how to request and print the channel's ID, title, and view count using the channels.list API method.\u003c/p\u003e\n"]]],["This guide outlines setting up a Ruby command-line application to interact with the YouTube Data API. Key actions include: enabling the YouTube Data API in the Google Developers Console, creating OAuth credentials, and downloading the `client_secret.json` file. Install the Google API client library using `gem install google-api-client`. A sample `quickstart.rb` file is then created and populated. Finally, the `ruby quickstart.rb` command runs the script, prompting for authorization which stores credentials for future use. This script retrieves and prints basic channel information for GoogleDevelopers.\n"],null,["# Ruby Quickstart\n\nComplete the steps described in the rest of this page, and in about five minutes\nyou'll have a simple Ruby command-line application that makes requests to the\nYouTube Data API.\nThe sample code used in this guide retrieves the `channel` resource for the GoogleDevelopers YouTube channel and prints some basic information from that resource.\n\nPrerequisites\n-------------\n\nTo run this quickstart, you'll need:\n\n- Ruby 2.0 or greater.\n- Access to the internet and a web browser.\n- A Google account.\n\nStep 1: Turn on the YouTube Data API\n------------------------------------\n\n1. Use\n [this wizard](https://console.developers.google.com/start/api?id=youtube)\n to create or select a project in the Google Developers Console and\n automatically turn on the API. Click **Continue** , then\n **Go to credentials**.\n\n2. On the **Create credentials** page, click the\n **Cancel** button.\n\n3. At the top of the page, select the **OAuth consent screen** tab.\n Select an **Email address** , enter a **Product name** if not\n already set, and click the **Save** button.\n\n4. Select the **Credentials** tab, click the **Create credentials**\n button and select **OAuth client ID**.\n\n5. Select the application type **Other** , enter the name\n \"YouTube Data API Quickstart\", and click the **Create** button.\n\n6. Click **OK** to dismiss the resulting dialog.\n\n7. Click the file_download\n (Download JSON) button to the right of the client ID.\n\n8. Move the downloaded file to your working directory and rename it\n `client_secret.json`.\n\nStep 2: Install the Google Client Library\n-----------------------------------------\n\nRun the following command to install the library: \n\n gem install google-api-client\n\nSee the library's [installation\npage](/api-client-library/ruby/start/installation) for the alternative\ninstallation options.\n\nStep 3: Set up the sample\n-------------------------\n\nCreate a file named `quickstart.rb` in your working directory and copy in the\nfollowing code:\n\n\n```ruby\n# Sample Ruby code for user authorization\n\nrequire 'rubygems'\ngem 'google-api-client', '\u003e0.7'\nrequire 'google/apis'\nrequire 'google/apis/youtube_v3'\nrequire 'googleauth'\nrequire 'googleauth/stores/file_token_store'\n\nrequire 'fileutils'\nrequire 'json'\n\n# REPLACE WITH VALID REDIRECT_URI FOR YOUR CLIENT\nREDIRECT_URI = 'http://localhost'\nAPPLICATION_NAME = 'YouTube Data API Ruby Tests'\n\n# REPLACE WITH NAME/LOCATION OF YOUR client_secrets.json FILE\nCLIENT_SECRETS_PATH = 'client_secret.json'\n\n# REPLACE FINAL ARGUMENT WITH FILE WHERE CREDENTIALS WILL BE STORED\nCREDENTIALS_PATH = File.join(Dir.home, '.credentials',\n \"youtube-quickstart-ruby-credentials.yaml\")\n\n# SCOPE FOR WHICH THIS SCRIPT REQUESTS AUTHORIZATION\nSCOPE = Google::Apis::YoutubeV3::AUTH_YOUTUBE_READONLY\n\ndef authorize\n FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))\n\n client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)\n token_store = Google::Auth::Stores::FileTokenStore.new(file: CREDENTIALS_PATH)\n authorizer = Google::Auth::UserAuthorizer.new(\n client_id, SCOPE, token_store)\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: REDIRECT_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization\"\n puts url\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: REDIRECT_URI)\n end\n credentials\nend\n\n# Initialize the API\nservice = Google::Apis::YoutubeV3::YouTubeService.new\nservice.client_options.application_name = APPLICATION_NAME\nservice.authorization = authorize\n\n# Sample ruby code for channels.list\n\ndef channels_list_by_username(service, part, **params)\n response = service.list_channels(part, params).to_json\n item = JSON.parse(response).fetch(\"items\")[0]\n\n puts (\"This channel's ID is #{item.fetch(\"id\")}. \" +\n \"Its title is '#{item.fetch(\"snippet\").fetch(\"title\")}', and it has \" +\n \"#{item.fetch(\"statistics\").fetch(\"viewCount\")} views.\")\nend\n\nchannels_list_by_username(service, 'snippet,contentDetails,statistics', for_username: 'GoogleDevelopers')\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/ruby/quickstart.rb\n```\n\n\u003cbr /\u003e\n\nStep 4: Run the sample\n----------------------\n\nRun the sample using the following command: \n\n ruby quickstart.rb\n\nThe first time you run the sample, it will prompt you to authorize access:\n\n1. The sample attempts to open a new window or tab in your default browser.\n If this fails, copy the URL from the console and manually open it in\n your browser.\n\n If you are not already logged into your Google account, you are\n prompted to log in. If you are logged into multiple Google accounts,\n you are asked to select one account to use for the authorization.\n2. Click the **Accept** button.\n3. Copy the code you're given, paste it into the command-line prompt, and press\n **Enter**. The code may appear in the URL of the page you are redirected to\n after granting authorization:\n\n ```\n http://localhost/?code=4/nr_1TspmmQPFyifh7nz...OFo#\n ```\n\nIt worked! **Great!** Check out the further reading section below to learn more.\nI got an error **Bummer.** Thanks for letting us know and we'll work to fix this quickstart.\n\nNotes\n-----\n\n- Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.\n- The authorization flow in this example is designed for a command-line application. For information on how to perform authorization in a web application, see [Using OAuth 2.0 for Web Server Applications](/youtube/v3/guides/auth/server-side-web-apps).\n\nFurther reading\n---------------\n\n- [Google Developers Console help documentation](/console/help/new)\n- [Google APIs Client for Ruby documentation](/api-client-library/ruby)\n- [YouTube Data API reference documentation](/youtube/v3/docs)"]]