Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse remote APIs (JSON and XML) using Rails 3

I am coding an app that is will be fetching data from different sources around the Internet via their respective API (JSON and XML).

How can I fetch this data (from remote source) and parse it using Rails 3? I looked everywhere on the net for a solution but it all seems very confusing too me.

Do anyone know of a good, simple gem that I can use for remote APIs? It was so simple in PHP.

like image 827
Jonathan Clark Avatar asked Feb 22 '11 11:02

Jonathan Clark


2 Answers

Try something like this for JSON

require 'open-uri'
require 'json'

result = JSON.parse(open("url_of_json_service").read)

See more abut the JSON gem here: http://flori.github.com/json/

Try something like this for XML

require 'open-uri'
require 'nokogiri'

result = Nokogiri.XML(open("url_of_xml_service").read)

See more about Nokogiri here: https://github.com/tenderlove/nokogiri (there are other XML parsers)

like image 177
DanSingerman Avatar answered Nov 16 '22 02:11

DanSingerman


Savon is a nice gem which will do the work for SOAP based requests(XML). Check out its documentation.

Here is a Railscast for understanding better.

For JSON based requests you can check @DanSingerman answer.

like image 21
Sachin Prasad Avatar answered Nov 16 '22 04:11

Sachin Prasad