7

I need to post some xml to a webservice and I'm trying to use HTTParty. Can someone provide an example as to how I go about doing so?

Here is the format of the XML I need to post:

<Candidate xmlns="com.mysite/2010/10/10" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<FirstName></FirstName>
<LastName></LastName>
<Email></Email>
<Gender></Gender>
</Candidate>

Here is my class so far:

require 'httparty'


class Webservice
  include HTTParty
  format :xml
  base_uri 'mysite.com'
  default_params :authorization => 'xxxxxxx'

  def self.add_candidate(first_name,last_name,email,gender)
    post('/test.xml', :body => "")    
  end  
end

I'm not quite sure how to flesh out add_candidate.

Any help would be appreciated.

Thanks.

Mike G
  • 379
  • 5
  • 11

1 Answers1

20

You've got two options. HTTParty allows you to post both a string or a hash.

The string version would be:

post('/test.xml', :body => "<Candidate xmlns=\"com.mysite/2010/10/10\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\"><FirstName>#{first_name}</FirstName><LastName>#{last_name}</LastName><Email>#{email}</Email><Gender>#{gender}</Gender></Candidate>")

Functional, but not pretty. I'd do this instead:

post('/test.xml', :body => {
  :Candidate => {
    :FirstName => first_name,
    :LastName  => last_name,
    :Email     => email,
    :Gender    => gender,
  }
}

Now, I can't say for sure whether the namespaces are required by the endpoint, and if so, whether the hash version will work. If that's the case, you may have to go with doing the body as a string.

vonconrad
  • 25,227
  • 7
  • 68
  • 69
  • No worries. If my solution solved the problem, please "accept" the answer by clicking the check mark to the left of my answer. You'll have an easier time getting answers to other questions that way. – vonconrad Sep 24 '10 at 01:06
  • 1
    I like your pretty version. How would you add an attribute to one of the elements? Say :Email needed an attribute call 'foo' with value 'bar'. How would you do that? – doremi Aug 07 '12 at 19:02
  • 1
    Note that this doesn't convert to XML on the client side, instead, it just posts a bunch of HTTP variables. For existing web services that expect XML, this is not really an alternative. Instead, you could use ActiveSupport's `to_xml` function that gets added to the Hash. – Pelle Dec 07 '13 at 23:11
  • You just save my day. – Malware Skiddie May 01 '17 at 16:32