Search code examples
rubygoogle-apiservice-accountsgoogle-api-ruby-clientgoogle-api-webmasters

How to use auth token in Google API (Ruby) WebmastersV3 (service account access)


I cannot connect the two pieces together: I am able to authenticate my service account and I know how to form the request for the information I need to retrieve from the API, but I cannot figure out how to make that request authenticated with the token.

This builds an object from the credential file I got for the service account and generates token successfully:

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!

The final request is like

wt_service.query_search_analytics(website, {
  "startDate"=> "2019-12-01",
  "endDate"=> "2019-12-02",
  "dimensions"=> [
    "query"
  ]
})

But the object for the webmaster tools API endpoint does not accept any arguments:

wt_service = Google::Apis::WebmastersV3::WebmastersService.new

But I need to somehow build it in an authenticated way, that is with the token - but how if I cannot add arguments?!

How do I build the object with the token?

=====

The response from Chadwick Wood solved it. There was a followup issue because Google API was using inconsistent variable names, so I'm pasting the full working code below (Works after adding the service user to webmaster tools user list for the domain)

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)

Solution

  • I think you just have to add:

    wt_service.authorization = authorizer
    

    ... after you create the service, and before you make the query. So:

    authorizer = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: File.open('service-account.json'), scope: scope)
    wt_service = Google::Apis::WebmastersV3::WebmastersService.new
    wt_service.authorization = authorizer
    wt_service.query_search_analytics ...