Create a SOAP Client
To create a new client based on a WSDL document, you could set the global :wsdl option by passing a Hash
to the Savon.client “factory method”. The client’s constructor accepts various
global options which are specific to a service.
client = Savon.client(wsdl: "https://example.com?wsdl")
Along with the simple Hash-based interface, Savon also comes with an interface based on blocks. If you’re passing a block to the constructor, it is executed using the instance_eval with delegation pattern.
client = Savon.client do
wsdl "https://example.com?wsdl"
end
The downside to this interface is, that it doesn’t allow you to use instance variables inside the block. You can only use local variables or call methods on your class. If you don’t mind typing a few more characters, you could accept an argument in your block and Savon will simply yield the global options to it. That way, you can use as many instance variables as you like.
client = Savon.client do |globals|
globals.wsdl @wsdl
end
In case your service doesn’t have a WSDL, you might need to provide Savon with various other options. For example, Savon needs to know about the SOAP endpoint and target namespace of your service.
client = Savon.client do
endpoint "https://example.com"
namespace "https://v1.example.com"
end
A nice little feature that comes with a WSDL, is that Savon can tell you about the available operations.
client.operations # => [:authenticate, :find_user]
But the client really exists to send SOAP messages, so let’s do that.
response = client.call(:authenticate, message: { username: "luke", password: "secret" })
Sending a request is all about options. #call takes the operation name plus any
local options that are specific to that request.
The #call method supports the same interface as the constructor. You can pass a simple Hash or
a block to use the instance_eval with delegation pattern.
response = client.call(:authenticate) do
message username: "luke", password: "secret"
soap_header "Token" => "secret"
end
You can also accept an argument in your block and Savon will yield the local options to it.
response = client.call(:authenticate) do |locals|
locals.message username: "luke", password: "secret"
locals.wsse_auth "luke", "secret", :digest
end