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 (https://code.google.com/apis/console/), and setting up a custom search account (with its prefs widened to all web pages - http://www.google.com/cse/)....

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

  require 'openssl'
  OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

  require 'google/api_client'
  client = Google::APIClient.new(:key => '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: