How to implement SOAP API Client in Ruby on Rails?

How to implement SOAP API Client in Ruby on Rails?

15 Sep 2022
0 Comments
How to implement SOAP API Client in Ruby on Rails?

SOAP(Simple Object Access Protocol) is a standard API protocol specification for exchanging structured information between computer systems and applications.

We can implement all the REST API methods like GET, POST, PUT and DELETE with SOAP API Client object in the Ruby on Rails application by using the ‘Savon’ gem.
 

Savon Gem Installation:

  • Step 1: Add the gem to Gemfile like this:
    gem ‘Savon’, ‘~> 2.12.0’
  • Step 2: Run bundle install


Example Usage:

  • Add require ‘Savon’ in the ruby file where you want to implement SOAP API calls.
  • Now create a client for the service which you want to access with SOAP protocols. See the example below:

client = Savon.client(wsdl: ‘http://service.example.com?wsdl')

  • Once a client object created, we can check the operations of the service by:

client.operations
# => [:find_user, :list_users]

  • For Get request on the above client operations, see below example:

# call the ‘listUsers’ operation
response = client.call(:list_users)

  • To find a particular user by id:

# call the ‘findUser’ operation
response = client.call(:find_user, message: { id: 42 })

  • response.body
    # => {find_user_response: { id: 42, name: ‘Hoff’ }}
  • For Post request, see below example:

client.call(:create_user, message: {name: ‘Jay’})

  • SOAP accepts some defined Global Options we can pass them while creating the client. See the below example:

namespaces = {

“xmlns:open” => “https://brandedpromoapparel.com/WebServices/PurchaseOrder.svc",

“xmlns:pss” => “http://www.promostandards.org/WSDL/PurchaseOrder/1.0.0/SharedObjects/"

}

# create a client for the service:

client = Savon.client(

wsdl: “https://brandedpromoapparel.com/WebServices/WSDL/POService.wsdl",

endpoint: “https://brandedpromoapparel.com/WebServices/PurchaseOrder.svc",

env_namespace: :soap,

soap_version: 2,

namespaces: namespaces,

namespace_identifier: ‘ps’,

log: true,

log_level: :debug,

pretty_print_xml: true,

ssl_verify_mode: :none

)

If you want to check each of these options in detail, here sharing the Savon gem reference link, you can check here: https://www.savonrb.com/version2


Thanks for reading!

Hope it helps you with SOAP client implementation. For any queries, please reach out to us in the comment section.




Leave a comment: