Searching Google Using SOAP Over the past few years, the SOAP standard has gathered a lot of support, in part because it is now officially documented by the World Wide Web Consortium (W3C). Standardization makes working with most SOAP services dependable, at least as far as the information you need to know and the information you can reasonably expect to get back. Because of the W3C backing, it could be said that SOAP is now the preferred architecture for most web services. Creating a SOAP client takes four simple steps:
Create an instance of a SOAP driver
Define the SOAP methods you want to call
Call the SOAP methods
Use the results in your Rails application
To use the Google search API (and to test the sample code), you'll need a free Google Developer's Key, which you can get directly from Google at https://www.google.com/accounts/NewAccount?continue=http://api.google.com/createkey&followup=http://api.google.com/createkey.
Here's a controller that uses SOAP to find the first three results from a Google search. Update the code_controller.rb file from the previous example to contain this new googletest method: class CodeController < ApplicationController def googletest yourkey = 'YOUR GOOGLE DEVELOPER KEY' # Your Google dev key @yourquery = 'SEARCH TEXT' # Search value XSD::Charset.encoding = 'UTF8' # Set encoding for response googleurl = "http://api.google.com/search/beta2" urn = "urn:GoogleSearch" driver = SOAP::RPC::Driver.new(googleurl, urn) # Create our driver driver.add_method('doGoogleSearch', 'key', 'q', # Set up methods we'll call 'start', 'maxResults', 'filter', 'restrict', 'safeSearch', 'lr', 'ie', 'oe') @result = driver.doGoogleSearch(yourkey, # make our SOAP request @yourquery, 0, 3, false, '', false, '', '', '') end end
Here's the code for the view. Save it as googletest.rhtml in your app/views/code/ directory: Query for: <%= @yourquery %><br> Found: <%= @result.estimatedTotalResultsCount %><br> Query took about <%= @result.searchTime %> seconds<br> <% @result.resultElements.each do |rec| %> <b>Title:</b> <%= rec["title"] %><br> <b>Summary:</b> <%= rec.snippet %><br> <b>Link:</b> <a href="<%= rec["URL"] %>"><%= rec["URL"] %></a> <br><br> <% end %>