Ruby-Codebeispiele
Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Für YouTube Analytics API sind die folgenden Codebeispiele verfügbar, in denen die Google APIs-Clientbibliothek für Ruby verwendet wird. Sie können diese Codebeispiele aus dem Ordner ruby
des YouTube APIs-Codebeispielrepositorys auf GitHub herunterladen.
Anfrage autorisieren
Im folgenden Codebeispiel wird die OAuth 2.0-Autorisierung durchgeführt, indem geprüft wird, ob eine lokale Datei mit Autorisierungsanmeldedaten vorhanden ist. Wenn die Datei nicht vorhanden ist, öffnet das Skript einen Browser und wartet auf eine Antwort. Anschließend werden die zurückgegebenen Anmeldedaten lokal gespeichert.
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'json'
require 'launchy'
require 'thin'
RESPONSE_HTML = <<stop
<html>
<head>
<title>OAuth 2 Flow Complete</title>
</head>
<body>
You have successfully completed the OAuth 2 flow. Please close this browser window and return to your program.
</body>
</html>
stop
FILE_POSTFIX = '-oauth2.json'
# Small helper for the sample apps for performing OAuth 2.0 flows from the command
# line. Starts an embedded server to handle redirects.
class CommandLineOAuthHelper
def initialize(scope)
credentials = Google::APIClient::ClientSecrets.load
@authorization = Signet::OAuth2::Client.new(
:authorization_uri => credentials.authorization_uri,
:token_credential_uri => credentials.token_credential_uri,
:client_id => credentials.client_id,
:client_secret => credentials.client_secret,
:redirect_uri => credentials.redirect_uris.first,
:scope => scope
)
end
# Request authorization. Checks to see if a local file with credentials is present, and uses that.
# Otherwise, opens a browser and waits for response, then saves the credentials locally.
def authorize
credentialsFile = $0 + FILE_POSTFIX
if File.exist? credentialsFile
File.open(credentialsFile, 'r') do |file|
credentials = JSON.load(file)
@authorization.access_token = credentials['access_token']
@authorization.client_id = credentials['client_id']
@authorization.client_secret = credentials['client_secret']
@authorization.refresh_token = credentials['refresh_token']
@authorization.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).ceil
if @authorization.expired?
@authorization.fetch_access_token!
save(credentialsFile)
end
end
else
auth = @authorization
url = @authorization.authorization_uri().to_s
server = Thin::Server.new('0.0.0.0', 8080) do
run lambda { |env|
# Exchange the auth code & quit
req = Rack::Request.new(env)
auth.code = req['code']
auth.fetch_access_token!
server.stop()
[200, {'Content-Type' => 'text/html'}, RESPONSE_HTML]
}
end
Launchy.open(url)
server.start()
save(credentialsFile)
end
return @authorization
end
def save(credentialsFile)
File.open(credentialsFile, 'w', 0600) do |file|
json = JSON.dump({
:access_token => @authorization.access_token,
:client_id => @authorization.client_id,
:client_secret => @authorization.client_secret,
:refresh_token => @authorization.refresh_token,
:token_expiry => @authorization.expires_at
})
file.write(json)
end
end
end
Die 10 besten Videos nach Aufrufen abrufen
In diesem Beispiel wird die reports.query
-Methode der API aufgerufen, um YouTube Analytics-Daten abzurufen.
Standardmäßig werden im Bericht die 10 besten Videos nach Aufrufzahlen abgerufen. Für diese Videos werden mehrere Messwerte zurückgegeben und die Ergebnisse werden in umgekehrter Reihenfolge nach Aufrufzahlen sortiert. Durch das Festlegen von Befehlszeilenparametern können Sie denselben Code auch zum Abrufen anderer Berichte verwenden.
#!/usr/bin/ruby
require 'rubygems'
gem 'google-api-client', '>0.7'
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/file_storage'
require 'google/api_client/auth/installed_app'
require 'trollop'
# These OAuth 2.0 access scopes allow for read-only access to the authenticated
# user's account for both YouTube Data API resources and YouTube Analytics Data.
YOUTUBE_SCOPES = ['https://www.googleapis.com/auth/youtube.readonly',
'https://www.googleapis.com/auth/yt-analytics.readonly']
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
YOUTUBE_ANALYTICS_API_SERVICE_NAME = 'youtubeAnalytics'
YOUTUBE_ANALYTICS_API_VERSION = 'v1'
def get_authenticated_services
client = Google::APIClient.new(
:application_name => $PROGRAM_NAME,
:application_version => '1.0.0'
)
youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)
youtube_analytics = client.discovered_api(YOUTUBE_ANALYTICS_API_SERVICE_NAME, YOUTUBE_ANALYTICS_API_VERSION)
file_storage = Google::APIClient::FileStorage.new("#{$PROGRAM_NAME}-oauth2.json")
if file_storage.authorization.nil?
client_secrets = Google::APIClient::ClientSecrets.load
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => YOUTUBE_SCOPES
)
client.authorization = flow.authorize(file_storage)
else
client.authorization = file_storage.authorization
end
return client, youtube, youtube_analytics
end
def main
now = Time.new.to_i
seconds_in_day = 60 * 60 * 24
seconds_in_week = seconds_in_day * 7
one_day_ago = Time.at(now - seconds_in_day).strftime('%Y-%m-%d')
one_week_ago = Time.at(now - seconds_in_week).strftime('%Y-%m-%d')
opts = Trollop::options do
opt :metrics, 'Report metrics', :type => String, :default => 'views,comments,favoritesAdded,favoritesRemoved,likes,dislikes,shares'
opt :dimensions, 'Report dimensions', :type => String, :default => 'video'
opt 'start-date', 'Start date, in YYYY-MM-DD format', :type => String, :default => one_week_ago
opt 'end-date', 'Start date, in YYYY-MM-DD format', :type => String, :default => one_day_ago
opt 'start-index', 'Start index', :type => :int, :default => 1
opt 'max-results', 'Max results', :type => :int, :default => 10
opt :sort, 'Sort order', :type => String, :default => '-views'
end
client, youtube, youtube_analytics = get_authenticated_services
begin
# Retrieve the channel resource for the authenticated user's channel.
channels_response = client.execute!(
:api_method => youtube.channels.list,
:parameters => {
:mine => true,
:part => 'id'
}
)
channels_response.data.items.each do |channel|
opts[:ids] = "channel==#{channel.id}"
# Call the Analytics API to retrieve a report. For a list of available
# reports, see:
# https://developers.google.com/youtube/analytics/v1/channel_reports
analytics_response = client.execute!(
:api_method => youtube_analytics.reports.query,
:parameters => opts
)
puts "Analytics Data for Channel #{channel.id}"
analytics_response.data.columnHeaders.each do |column_header|
printf '%-20s', column_header.name
end
puts
analytics_response.data.rows.each do |row|
row.each do |value|
printf '%-20s', value
end
puts
end
end
rescue Google::APIClient::TransmissionError => e
puts e.result.body
end
end
main
Sofern nicht anders angegeben, sind die Inhalte dieser Seite unter der Creative Commons Attribution 4.0 License und Codebeispiele unter der Apache 2.0 License lizenziert. Weitere Informationen finden Sie in den Websiterichtlinien von Google Developers. Java ist eine eingetragene Marke von Oracle und/oder seinen Partnern.
Zuletzt aktualisiert: 2025-08-21 (UTC).
[null,null,["Zuletzt aktualisiert: 2025-08-21 (UTC)."],[[["\u003cp\u003eThis page provides Ruby code samples for using the YouTube Analytics API.\u003c/p\u003e\n"],["\u003cp\u003eThe samples demonstrate OAuth 2.0 authorization for accessing user data and retrieving YouTube Analytics reports.\u003c/p\u003e\n"],["\u003cp\u003eYou can find the complete code samples in the \u003ccode\u003eruby\u003c/code\u003e folder of the \u003ca href=\"https://github.com/youtube/api-samples\"\u003eYouTube APIs code sample repository on GitHub\u003c/a\u003e.\u003c/p\u003e\n"],["\u003cp\u003eOne sample focuses on authorizing requests by utilizing local credentials or initiating an OAuth flow if necessary.\u003c/p\u003e\n"],["\u003cp\u003eAnother sample retrieves the top 10 videos by viewcount and can be customized to retrieve other report data by setting command line parameters.\u003c/p\u003e\n"]]],["The provided code demonstrates using the Google APIs Client Library for Ruby with the YouTube Analytics API. It outlines two core actions: authorizing requests and retrieving data. Authorization involves checking for local credentials or initiating a browser-based OAuth 2.0 flow, saving credentials upon completion. Data retrieval involves using the `reports.query` method to fetch YouTube Analytics, defaulting to the top 10 videos by viewcount and returning various metrics, customizable via command-line parameters.\n"],null,["# Ruby Code Samples\n\nThe following code samples, which use the [Google APIs Client Library for Ruby](/api-client-library/ruby), are available for the YouTube Analytics API. You can download these code samples from the `ruby` folder of the [YouTube APIs code sample repository on GitHub](https://github.com/youtube/api-samples).\n\nAuthorize a request\n-------------------\n\nThe following code sample performs OAuth 2.0 authorization by checking for the presence of a local\nfile that contains authorization credentials. If the file is not present, the script opens a browser and waits\nfor a response, then saves the returned credentials locally. \n\n```ruby\nrequire 'google/api_client'\nrequire 'google/api_client/client_secrets'\nrequire 'json'\nrequire 'launchy'\nrequire 'thin'\n\nRESPONSE_HTML = \u003c\u003cstop\n\u003chtml\u003e\n \u003chead\u003e\n \u003ctitle\u003eOAuth 2 Flow Complete\u003c/title\u003e\n \u003c/head\u003e\n \u003cbody\u003e\n You have successfully completed the OAuth 2 flow. Please close this browser window and return to your program.\n \u003c/body\u003e\n\u003c/html\u003e\nstop\n\nFILE_POSTFIX = '-oauth2.json'\n\n# Small helper for the sample apps for performing OAuth 2.0 flows from the command\n# line. Starts an embedded server to handle redirects.\nclass CommandLineOAuthHelper\n\n def initialize(scope)\n credentials = Google::APIClient::ClientSecrets.load\n @authorization = Signet::OAuth2::Client.new(\n :authorization_uri =\u003e credentials.authorization_uri,\n :token_credential_uri =\u003e credentials.token_credential_uri,\n :client_id =\u003e credentials.client_id,\n :client_secret =\u003e credentials.client_secret,\n :redirect_uri =\u003e credentials.redirect_uris.first,\n :scope =\u003e scope\n )\n end\n\n # Request authorization. Checks to see if a local file with credentials is present, and uses that.\n # Otherwise, opens a browser and waits for response, then saves the credentials locally.\n def authorize\n credentialsFile = $0 + FILE_POSTFIX\n\n if File.exist? credentialsFile\n File.open(credentialsFile, 'r') do |file|\n credentials = JSON.load(file)\n @authorization.access_token = credentials['access_token']\n @authorization.client_id = credentials['client_id']\n @authorization.client_secret = credentials['client_secret']\n @authorization.refresh_token = credentials['refresh_token']\n @authorization.expires_in = (Time.parse(credentials['token_expiry']) - Time.now).ceil\n if @authorization.expired?\n @authorization.fetch_access_token!\n save(credentialsFile)\n end\n end\n else\n auth = @authorization\n url = @authorization.authorization_uri().to_s\n server = Thin::Server.new('0.0.0.0', 8080) do\n run lambda { |env|\n # Exchange the auth code & quit\n req = Rack::Request.new(env)\n auth.code = req['code']\n auth.fetch_access_token!\n server.stop()\n [200, {'Content-Type' =\u003e 'text/html'}, RESPONSE_HTML]\n }\n end\n\n Launchy.open(url)\n server.start()\n\n save(credentialsFile)\n end\n\n return @authorization\n end\n\n def save(credentialsFile)\n File.open(credentialsFile, 'w', 0600) do |file|\n json = JSON.dump({\n :access_token =\u003e @authorization.access_token,\n :client_id =\u003e @authorization.client_id,\n :client_secret =\u003e @authorization.client_secret,\n :refresh_token =\u003e @authorization.refresh_token,\n :token_expiry =\u003e @authorization.expires_at\n })\n file.write(json)\n end\n end\nend\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/ruby/oauth/oauth_util.rb\n```\n\nRetrieve top 10 videos by viewcount\n-----------------------------------\n\nThis sample calls the API's `reports.query` method to retrieve YouTube Analytics data.\nBy default, the report retrieves the top 10 videos based on viewcounts, and it returns several metrics for those\nvideos, sorting the results in reverse order by viewcount. By setting command line parameters, you can use the same\ncode to retrieve other reports as well. \n\n```ruby\n#!/usr/bin/ruby\n\nrequire 'rubygems'\ngem 'google-api-client', '\u003e0.7'\nrequire 'google/api_client'\nrequire 'google/api_client/client_secrets'\nrequire 'google/api_client/auth/file_storage'\nrequire 'google/api_client/auth/installed_app'\nrequire 'trollop'\n\n# These OAuth 2.0 access scopes allow for read-only access to the authenticated\n# user's account for both YouTube Data API resources and YouTube Analytics Data.\nYOUTUBE_SCOPES = ['https://www.googleapis.com/auth/youtube.readonly',\n 'https://www.googleapis.com/auth/yt-analytics.readonly']\nYOUTUBE_API_SERVICE_NAME = 'youtube'\nYOUTUBE_API_VERSION = 'v3'\nYOUTUBE_ANALYTICS_API_SERVICE_NAME = 'youtubeAnalytics'\nYOUTUBE_ANALYTICS_API_VERSION = 'v1'\n\ndef get_authenticated_services\n client = Google::APIClient.new(\n :application_name =\u003e $PROGRAM_NAME,\n :application_version =\u003e '1.0.0'\n )\n youtube = client.discovered_api(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION)\n youtube_analytics = client.discovered_api(YOUTUBE_ANALYTICS_API_SERVICE_NAME, YOUTUBE_ANALYTICS_API_VERSION)\n\n file_storage = Google::APIClient::FileStorage.new(\"#{$PROGRAM_NAME}-oauth2.json\")\n if file_storage.authorization.nil?\n client_secrets = Google::APIClient::ClientSecrets.load\n flow = Google::APIClient::InstalledAppFlow.new(\n :client_id =\u003e client_secrets.client_id,\n :client_secret =\u003e client_secrets.client_secret,\n :scope =\u003e YOUTUBE_SCOPES\n )\n client.authorization = flow.authorize(file_storage)\n else\n client.authorization = file_storage.authorization\n end\n\n return client, youtube, youtube_analytics\nend\n\ndef main\n now = Time.new.to_i\n seconds_in_day = 60 * 60 * 24\n seconds_in_week = seconds_in_day * 7\n one_day_ago = Time.at(now - seconds_in_day).strftime('%Y-%m-%d')\n one_week_ago = Time.at(now - seconds_in_week).strftime('%Y-%m-%d')\n\n opts = Trollop::options do\n opt :metrics, 'Report metrics', :type =\u003e String, :default =\u003e 'views,comments,favoritesAdded,favoritesRemoved,likes,dislikes,shares'\n opt :dimensions, 'Report dimensions', :type =\u003e String, :default =\u003e 'video'\n opt 'start-date', 'Start date, in YYYY-MM-DD format', :type =\u003e String, :default =\u003e one_week_ago\n opt 'end-date', 'Start date, in YYYY-MM-DD format', :type =\u003e String, :default =\u003e one_day_ago\n opt 'start-index', 'Start index', :type =\u003e :int, :default =\u003e 1\n opt 'max-results', 'Max results', :type =\u003e :int, :default =\u003e 10\n opt :sort, 'Sort order', :type =\u003e String, :default =\u003e '-views'\n end\n\n client, youtube, youtube_analytics = get_authenticated_services\n\n begin\n # Retrieve the channel resource for the authenticated user's channel.\n channels_response = client.execute!(\n :api_method =\u003e youtube.channels.list,\n :parameters =\u003e {\n :mine =\u003e true,\n :part =\u003e 'id'\n }\n )\n\n channels_response.data.items.each do |channel|\n opts[:ids] = \"channel==#{channel.id}\"\n\n # Call the Analytics API to retrieve a report. For a list of available\n # reports, see:\n # https://developers.google.com/youtube/analytics/v1/channel_reports\n analytics_response = client.execute!(\n :api_method =\u003e youtube_analytics.reports.query,\n :parameters =\u003e opts\n )\n\n puts \"Analytics Data for Channel #{channel.id}\"\n\n analytics_response.data.columnHeaders.each do |column_header|\n printf '%-20s', column_header.name\n end\n puts\n\n analytics_response.data.rows.each do |row|\n row.each do |value|\n printf '%-20s', value\n end\n puts\n end\n end\n rescue Google::APIClient::TransmissionError =\u003e e\n puts e.result.body\n end\nend\n\nmain\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/ruby/yt_analytics_report.rb\n```"]]