Interfacing with a third-party API in Rails? ( Opeing URLs and Parsing XML/JSON )
for opening urls you can use open-uri
just
require 'open-uri'file_handle = open("http://google.com/blah.xml")
to parse xml you can use Nokogiri
$ gem install nokogiri
document = Nokogiri::XML(file_handle)document/"xpath/search"
very powerful library, can do all kinds of searching and modifying for both XML and HTML
same for html Nokogiri::HTML
there is also lots of JSOM support out there too
checkout Nokogiri also Hpricot is good for XML/HTML
for JSON in rails
parsed_json = ActiveSupport::JSON.decode(your_json_string)parsed_json["results"].each do |longUrl, convertedUrl| site = Site.find_by_long_url(longUrl) site.short_url = convertedUrl["shortUrl"] site.saveend
see this question:How do I parse JSON with Ruby on Rails?
In a perfect world, a gem already exists for the API you want to use, and you would just use that. Otherwise, you have a few options:
- ActiveResource might make sense for you depending on the complexity of the API you want to use. For example, here's an old (and no longer functional) example of using ActiveResource to connect to the Twitter API
- Net::Http is lower-level, but certainly does the trick
- open-uri is a wrapper for net/http
- Curb uses libcurl to get things done
Parsing JSON is generally very straightforward. For XML, as stated in another answer, Nokogiri is probably the way to go.