Article / December 30, 2008

Consuming SOAP with Ruby, and SOAP::Mapping::Object

By Dylan Stamat/2262 Views/1 Comment

There are still plenty of SOAP API's out in the wild, and you may have to interface with them at some point.
If you're simply wanting to consume data from an external source, then soap4r is your library.

Here's a basic connection to an external SOAP server:

require 'soap/wsdlDriver'
wsdl   = "http://example.com/soap/api/our_api.wsdl
driver = SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver

Now that you have the driver instantiated, you can go ahead and use it. You may need to view the actual WSDL file in order to see what calls are available. In the example above, if we saw the WSDL had something like this:

<xsd:element name="search">
  </xsd:element><xsd:complextype>
    </xsd:complextype><xsd:sequence>
      </xsd:sequence><xsd:element maxoccurs="1" name="yourKey" nillable="true" type="xsd:string" minoccurs="1">
      </xsd:element><xsd:element maxoccurs="1" name="yourAccountNumber" nillable="true" type="xsd:string" minoccurs="1">
</xsd:element>

... we could assume a "search" method was available, and could take "yourKey" and "yourAccountNumber" parameters.

>> driver.search("myKey", "123456")
#<SOAP::Mapping::Object:0x9046d8 {http://api.example.com}out=#<SOAP::Mapping::Object:0x903a44 {http://api.example.com}count="50" {http://api.example.com}offset="0" {http://api.example.com}products=#<SOAP::Mapping::Object:0x8fe9ea... etc

Most likely, you'll get back some crazy looking results composed of many SOAP::Mapping::Object's. The method to parse this structure is not well documented, and you'll need to access the data via string based hash lookups.

results = driver.search("myKey", "123456")
results['out']['products']['product']

In a production scenario, you'd probably want to build the remote WSDL into a local library of objects, which can be done using wsdl2ruby, which is packaged with soap4r.

Hope that helps, and raise your glass to the transparency that is REST and XMLRPC!

Add a Comment