I'm working on a Rails project which will need to interface with multiple third-party APIs. I'm pretty new to Rails, and I've never done this before, so I'm lacking some basic information here. Specifically, What is the preferred Rails way of simply querying an external URL?
In the PHP world, it was cURL. You take whatever the resource URL is, throw cURL at it, and start processing the response, whether it be XML, JSON, etc.
So, what's the cURL equivalent in Rails? While we're at it, what is the preferred method of parsing XML and JSON responses? My instincts are to Google around for some Ruby gems to get the job done, but this is such a practical problem that I wouldn't be surprised if the Rails community had already worked out a tried-and-true solution to this kind of problem.
If it's of any contextual value, I plan to run these third-party API interactions as nightly cronjobs, probably all packaged up as custom rake tasks.
Thanks for sharing your expertise.
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.save
end
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:
Parsing JSON is generally very straightforward. For XML, as stated in another answer, Nokogiri is probably the way to go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With