【发布时间】:2019-12-26 10:19:27
【问题描述】:
我无法将这两个部分连接在一起:我能够验证我的服务帐户,并且我知道如何形成对我需要从 API 检索的信息的请求,但我不知道如何使该请求通过身份验证令牌。
这会根据我为服务帐户获取的凭据文件构建一个对象并成功生成令牌:
需要“googleauth”
require 'google/apis/webmasters_v3'
website = "https://example.com"
scope = 'https://www.googleapis.com/auth/webmasters'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('service-account.json'),
scope: scope)
token = authorizer.fetch_access_token!
最终的请求是这样的
wt_service.query_search_analytics(website, {
"startDate"=> "2019-12-01",
"endDate"=> "2019-12-02",
"dimensions"=> [
"query"
]
})
但网站管理员工具 API 端点的对象不接受任何参数:
wt_service = Google::Apis::WebmastersV3::WebmastersService.new
但是我需要以某种经过身份验证的方式构建它,即使用令牌 - 但是如果我不能添加参数怎么办?!
如何使用令牌构建对象?
=====
Chadwick Wood 的回应解决了这个问题。由于 Google API 使用的变量名称不一致,因此出现了后续问题,因此我将完整的工作代码粘贴在下面(将服务用户添加到域的网站管理员工具用户列表后工作)
require 'googleauth'
require 'google/apis/webmasters_v3'
website = "https://example.com"
scope = 'https://www.googleapis.com/auth/webmasters'
authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: File.open('service-account.json'),scope: scope)
token = authorizer.fetch_access_token!
wt_service = Google::Apis::WebmastersV3::WebmastersService.new
wt_service.authorization = authorizer
wt_service.authorization.apply(token)
request_object = {
start_date: "2019-02-01",
end_date: "2020-02-28",
dimensions: ["query"]
}
params = Google::Apis::WebmastersV3::SearchAnalyticsQueryRequest.new(request_object)
res = wt_service.query_search_analytics(website, params)
【问题讨论】:
-
文档中哪里说web master api支持服务账户?
-
那是客户端库而不是 API,即使它们不支持某些内容,所有 api 的库都是相同的。它在文档或 Google 网站管理员工具中的哪个位置声明它支持服务帐户?
-
亲爱的@DalmTo,您能不能非常好心地告诉我一种不涉及服务帐户的方式从 Ruby 访问 Google Webmasters API 的方法?
标签: ruby google-api service-accounts google-api-ruby-client google-api-webmasters