Saturday, July 14, 2012

Google-api-client Authorizing with an API Key in Ruby

The documentation for the Google RESTful APIs is generally pretty good, however when playing with the google-api-client ruby gem, developed by Google to trawl their APIs, I ran into a few issues, particularly when authenticating using an api key (rather than OAuth).

After installing the google-api-client gem, getting a Google API Key (, and setting up a custom search account (with its prefs widened to all web pages -

The following allowed me to trawl google search results (copy paste into irb, then inspect response when finished):

  require 'openssl'

  require 'google/api_client'
  client = => 'your-api-key', :authorization => nil)
  search = client.discovered_api('customsearch')

  response = client.execute(
    :api_method => search.cse.list,
    :parameters => {
      'q' => 'the hoff',
      'key' => 'your-api-key',
      'cx' => 'your-custom-search-id'

THE MOST IMPORTANT BIT was the :authorization param when constructing he client.... this ensures the api key is used when calling, in preference to oauth. Without it you will get 401 Unauthorized response status everytime.

No comments: