Search code examples
google-app-engineruby-on-rails-4google-api-clientgoogle-custom-search

Image Search Example via Rails Google API Client


I need to replicate "Search Google for this Image" in my rails app where image search is performed on an image in the app. I am using google-api-ruby-client gem. To test the api I am starting with a simple query search:

Trying this for a regular search term but getting invalid_scope error.

client               = Google::APIClient.new application_name: 'xxx', application_version: '1.0'
keypath              = Rails.root.join('config', 'privatekey.p12').to_s
key                  = Google::APIClient::PKCS12.load_key(keypath, 'notasecret')

client.authorization = Signet::OAuth2::Client.new(
    :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',
    :audience             => 'https://accounts.google.com/o/oauth2/token',
    :scope                => 'https://www.googleapis.com/customsearch/v1',
    :issuer               => 'xxx@developer.gserviceaccount.com',
    :signing_key          => key
).tap { |auth| auth.fetch_access_token! }


api_method = client.discovered_api('customsearch', 'v1')

result = client.execute(:api_method => api_method, :parameters => {
    'q'          => 'Hello+World'
})
return result.data

Thoughts?


Solution

  • It looks like your API call is missing the required Custom Search Engine ID. You need to use cx or cref to specify the custom search engine you want to use. If you don't already have CSE ID, you can get one here: https://www.google.com/cse

    Once you have the CSE ID, you will need to include it to the parameters. One possible way is just adding it to the hash you already have...

    result = client.execute(:api_method => api_method, :parameters => {'cx' => 'YOUR_CSE_ID', 'q'=> 'Hello+World'}
    

    Your actual URI structure should look like:

    https://www.googleapis.com/customsearch/v1?key=YOUR_API_KEY&cx=YOUR_CSE_ID&q=Hello+World
    

    Here's another good reference: https://developers.google.com/custom-search/docs/api