TaxCloud: SOAP Service Integration in Ruby

Back | ruby, open source, testing | 11/27/2012 |

image

I’ve been working on the the tax_cloud gem for the past couple of days and am happy to announce version 0.2.0, released today. The gem was started by @tempelmeyer and is now a mature wrapper for the TaxCloud US Sales Tax calculation service.

This library is also a nice example of a generic SOAP client wrapper in Ruby. I wanted to point out several successful patterns for this integration, which I cannot take credit for, for the most part.

Error Handling

I borrowed error handling from @modetojoy’s Mongoid. Today someone said: “I had a bug in a spec and Durran told me how to fix it in an error message.” True story. To accomplish this we define a base error that holds the problem, summary and resolution. In tax_cloud’s case this is  TaxCloud::Errors::TaxCloudError paired with config/locales/en.yml, a locale file that does the error formatting. There’re two things to do in order for the error code to find the message: add the locale file to the load path, in tax_cloud.rb, and do a bit of formatting with I18n.

  1. I18n.load_path << File.join(File.dirname(__FILE__), "config", "locales", "en.yml")

  1. def translate(key, options)
  2.     ::I18n.translate("#{BASE_KEY}.#{key}", { :locale => :en }.merge(options)).strip
  3. end

What does an error in tax_cloud look like?

  1. Problem:
  2.   Missing configuration.
  3. Summary:
  4.   TaxCloud requires an API login ID and key.
  5. Resolution:
  6.   Create a TaxCloud merchant account at http://www.taxcloud.net.
  7.   Add a website to your TaxCloud account.
  8.   This will generate an API ID and API Key that you will need to use the service.
  9.   Configure the TaxCloud gem. For example, add the following to `config/initializers/tax_cloud.rb`.
  10.   TaxCloud.configure do |config|
  11.    config.api_login_id = 'your_tax_cloud_api_login_id'
  12.    config.api_key = 'your_tax_cloud_api_key'
  13.    config.usps_username = 'your_usps_username' # optional
  14.   end

Pretty awesome.

Safe SOAP Requests

The tax_cloud gem uses Savon to make SOAP requests. “Savon” is French for “Soap”, which confuses the French speakers like myself trying to explain that SOAP is Savon. Anyway, a client is initialized with its WSDL.

  1. module TaxCloud #:nodoc:
  2.   class Client < Savon::Client
  3.     def initialize
  4.       super 'https://api.taxcloud.net/1.0/?wsdl'
  5.     end
  6.   end
  7. end

First, we need to add authentication to every request, which is required by the API. We can override request.

  1. def request(method, body = {})
  2.     super method, :body => body.merge(auth_params)
  3. end
  4.  
  5. def auth_params
  6. {
  7.     'apiLoginID' => TaxCloud.configuration.api_login_id,
  8.     'apiKey' => TaxCloud.configuration.api_key
  9. }
  10. end

Second, we want to handle SOAP errors, and give a detailed explanation for SOAP faults, Mongoid-style. This is your typical block with yield.

  1. def request(method, body = {})
  2.   safe do
  3.     super method, :body => body.merge(auth_params)
  4.   end
  5. end
  6.  
  7. def safe &block
  8.   begin
  9.     yield
  10.   rescue Savon::SOAP::Fault => e
  11.     raise TaxCloud::Errors::SoapError.new(e)
  12.   end
  13. end

The complete code can be found in client.rb. The error itself is parsed in soap_error.rb – SOAP faults come in standard format.

Parsing Responses

We will now raise a good-looking exception on SOAP failures, but we still must protect ourselves from unexpected data or successful SOAP requests that return API errors. That possibility is the thing I detest most about SOAP (vs. REST) – it makes programming a client unnecessarily complicated. The TaxCloud service returns a SOAP body with different values in key_response/key_result/response_type, where the key will be the name of the method invoked (eg. ping_response). A bit of meta-programming can make a base class, which can parse a response and match an XML path, raising errors where appropriate. It can be subclassed into a generic response type and, finally, into specific declarative implementations such as ping or authorized.

Most services have a common response pattern, generalizing it yields a very productive framework where adding support for new calls requires very little to no code. And you must never, ever expose to the user that you’re making SOAP requests and return any kind of raw SOAP object. Return domain-specific classes with attributes on success and raise exceptions otherwise.

Testing SOAP Requests

The tax_cloud gem uses VCR to test SOAP requests. It’s surprisingly easy: use a cassette (a YAML file), which records it the first time you make a request. Second time around the file contents are used and no HTTP requests are made. You can filter out sensitive keys in the configuration.

  1. require 'vcr'
  2.  
  3. VCR.configure do |c|
  4.   c.cassette_library_dir = 'test/cassettes'
  5.   c.hook_into :webmock
  6.   c.filter_sensitive_data('api-login-id')  { TaxCloud.configuration.api_login_id }
  7.   c.filter_sensitive_data('api-key')       { TaxCloud.configuration.api_key }
  8.   c.filter_sensitive_data('usps-username') { TaxCloud.configuration.usps_username }  
  9. end

  1. def test_ping_with_invalid_credentials
  2.   assert_raise TaxCloud::Errors::ApiError do
  3.    VCR.use_cassette('ping_with_invalid_credentials') do
  4.     TaxCloud.client.ping
  5.    end
  6.   end
  7. end
  8.  
  9. def test_ping_with_invalid_response
  10.   e = assert_raise TaxCloud::Errors::UnexpectedSoapResponse do
  11.    VCR.use_cassette('ping_with_invalid_response') do
  12.     TaxCloud.client.ping
  13.    end
  14.   end
  15.   assert_equal "Expected a value for `ping_result`.", e.problem
  16. end
  17.  
  18. def test_ping
  19.   VCR.use_cassette('ping') do
  20.    response = TaxCloud.client.ping
  21.    assert_equal "OK", response
  22.   end
  23. end

You can see the rest of the tests here.

Finally

Let me know if you use some of these ideas, post your comments and suggestions and please help improve the tax_cloud gem on Github.