Search code examples
ruby-on-railsrubygoogle-searchgoogle-custom-search

Ruby Google Custom Seach API get results from next page


the code below is only getting the results from the first page of the google pagination... how to get more results?

require 'google/api_client'

# autenticação
client = Google::APIClient.new(:application_name => 'Ruby Drive sample',
      :application_version => '1.0.0', 
      :client_id => 'xxxxxxxxxxxxxxxx',
      :client_secret => 'xxxxxxxxxxxxxx',
      :authorization => nil)
search = client.discovered_api('customsearch')

# chama a API
response = client.execute(
  :api_method => search.cse.list,
    :parameters => {
      'q' => 'cafe',
      'key' => 'xxxxxxxxxxxx',
      'cx' => 'xxxxxxxxxxxxxxxx'
    }
)

# recebe a resposta em json
body = JSON.parse(response.body)
items = body['items']

# printa algumas informações...
items.each do |item|
  puts "#{item['formattedUrl']}"
end

Solution

  • Simply use the nextPageToken as a parameter in the next request until you get back a result without a nextPageToken key

    next_page_token = body['nextPageToken']
    
    response_page2 = client.execute(
      :api_method => search.cse.list,
      :parameters => {
        'nextPageToken' => next_page_token,
        'key' => 'xxxxxxxxxxxx',
        'cx' => 'xxxxxxxxxxxxxxxx'
      }
    )