2

I am using rest-client to make restful API calls. My response can be either in JSON or XML.

How can I easily parse the responses? It is pulling Company and Contact information.

Is there a way to treat each XML record as an object, so I can access the tags as methods?

What is the recommended way to access and traverse the response I get back, and is it XML or JSON as the recommended format?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Satchel
  • 16,414
  • 23
  • 106
  • 192

2 Answers2

0

In the Readme of the 'maintained' github repo for the ruby version of rest-client, there is a section on handling results.

Are you calling two different APIs? I'm unsure of how one API would be both returning XML and/or JSON?

Personally, I'd make the call with rest-client (instead of net::http or something) and then use REXML to then parse the information I needed.

example (hypothetical with no code):


api_call = RestClient.get 'http://example.com/resource'
xml  = REXML::Document.new(api_call)
#parse xml here

For information on parsing with REXML check out this tutorial

pjammer
  • 9,489
  • 5
  • 46
  • 56
  • how is REXML compared to hpricot...sounds like hpricot is a similar option? JSON is an option -- either it returns XML or JSON.... – Satchel Dec 25 '10 at 09:04
  • ah, ok, you have a choice. cool. REXML is an ruby xml parser, for lack of a better word. hpricot will go out and and grab the content and also parse the response but was built for html parsing. REXML is built into ruby and is fairly easy to parse. hpricot uses a more OO approach to parsing, but may not be as powerful as REXML. One less dependency for your app, etc. Hpricot is faster but unless you have a huge amount of data, it seems minimal imo. api calls usually aren't that huge but ymmv. – pjammer Dec 25 '10 at 13:07
  • Personally, I recommend [Nokogiri](http://nokogiri.org) over REXML or Hpricot. I've had bad experiences with Hpricot and REXML isn't as flexible as Nokogiri. Nokogiri is also supported really well by the developers. – the Tin Man Dec 26 '10 at 04:07
0

If you don't have to use xml json is very easy to get going especially with the rails helper 'to_json' which allows you to convert ruby objects/arrays etc... into javascript files and use dot notation to access objects. Accessing objects is essentially the same such as object.method for ruby on json albeit they are structured differently.

thenengah
  • 42,557
  • 33
  • 113
  • 157
  • 1
    how can I learn more about this? It sounds like if I have the option, JSON would be better to use...? – Satchel Dec 25 '10 at 09:03