A Ruby web service client

In previous blog posts I showed how I created a Java web service and client using Apache Axis2. In those examples I showed how to read from web service methods that return a single object, and also an array or list of objects. In this post I'll show several sample Ruby programs that also read from those same Java web services.

Here's the first Ruby client I created. I first hit the WSDL URL for the web service, then call the getUser method of the web service. Then I use the inspect to show the information that is returned by the call.

require 'soap/wsdlDriver'

WSDL_URL = "http://localhost:8080/axis2/services/UserService?wsdl"
factory = SOAP::WSDLDriverFactory.new(WSDL_URL)
driver = factory.create_rpc_driver

puts "USER: "
puts driver.getUser().inspect

My second approach

After creating that first web service I got a little more curious on how I would convert this User object into a Ruby User object, so I created this sample program:

require 'soap/rpc/driver'
require 'cgi'

class User
  attr :first_name, :last_name, :user_id
end

endpoint = 'http://localhost:8080/axis2/services/UserService'
namespace = 'http://service.pojo.sample'

soap = SOAP::RPC::Driver.new(endpoint, namespace)
soap.add_method('getUser')
remoteUser = soap.getUser

p remoteUser.firstName
p remoteUser.lastName
p remoteUser.userId

u = User.new
u.first_name = remoteUser.firstName
u.last_name = remoteUser.lastName
u.user_id = remoteUser.userId

Reading an array of objects

Finally, I created some sample Ruby code to show how I would read an array of objects from a web service. The Ruby source code for this solution is shown here:

require 'soap/rpc/driver'
require 'cgi'

endpoint = 'http://localhost:8080/axis2/services/UserService'
namespace = 'http://service.pojo.sample'

soap = SOAP::RPC::Driver.new(endpoint, namespace)
soap.add_method('getUserArray')
result = soap.getUserArray

first = result[0]
printf "%s %s %s\n", first.firstName, first.lastName, first.userId

second = result[1]
printf "%s %s %s\n", second.firstName, second.lastName, second.userId

For me one of the coolest things about how this all works is that I can just call these method names on the result object (which I didn't have to declare anywhere in my Ruby code), and everything just magically (dynamically) works. Very cool.