Extending Web Services Using Other Web Services

How to create a useful new Web service by tapping in to the power of two other freely available Web services.
Creating a Web Service

Now that we have created a combined lookup tool, how can we turn it into a Web service? (For the purposes of simplicity, I'm going to use XML-RPC. It would be equally valid to use SOAP or even to look for REST parameters.)

The answer is easier than you might think. We will need to modify the program to take its inputs from the Web instead of ARGV. We also will need to send the output over the XML-RPC, back to the client that sent the original request.

But the end result, as you can see in Listing 3, is not terribly different from what we had in Listing 2. And because it operates as a Web service, we can now incorporate its results into new programs that we might write. Better yet, we can create new Web services that use this service as an underlying foundation, thus stacking the functions even deeper, into even more useful libraries.

Listing 3 begins by creating a new instance of XMLRPC::Server on port 8080. It then adds a new handler, which we call atf.books, and which both accepts an array as input and returns one as output. Using Ruby's block notation, the handler then iterates over each ISBN that it receives via the XML-RPC method call.

The rest of the program is largely the same as combined-lookup.rb, with the exception of the output. Output to an XML-RPC method call, at least in this Ruby library, is accomplished by placing the output in the final line of the block. Because we plan to return an array, we need to create and populate the array. We thus define output variable as an empty array and add one element to it for each ISBN we check. Each element of that array then will be a hash (known as a struct in XML-RPC jargon), with the ISBN key pointing to the book's ISBN, and the New, Used and Collectible keys pointing to the prices retrieved from Amazon.

The server program then concludes with a call to server.serve, starting an infinite listener loop for a simple HTTP server.

To test this program, you need an RPC client; a simple one is shown in Listing 4 and takes its arguments from the command line. You'll notice that we use Ruby's exception-handling mechanism to watch for potential problems. If there is an error on the server, we can trap it and print a useful debugging message.