Consuming non-REST APIs in Rails with ActiveResource

前端 未结 3 542
眼角桃花
眼角桃花 2021-02-04 20:48

I\'m writing a client that consumes a non-REST API (i.e. GET site.com/gettreasurehunts), which requires that I specify all parameters (even the resource ID) in the request\'s HT

相关标签:
3条回答
  • 2021-02-04 21:26

    I don't think there is a way to do this with ActiveResource, for these cases I just use Net::HTTP and Nokogiri

    0 讨论(0)
  • 2021-02-04 21:28

    I would recommend HTTParty, it's pretty flexible and I'm sure capable of handling what you need.

    Some examples from the project:

    pp HTTParty.get('http://whoismyrepresentative.com/whoismyrep.php?zip=46544')
    pp HTTParty.get('http://whoismyrepresentative.com/whoismyrep.php', :query => {:zip => 46544})
    
    @auth = {:username => u, :password => p}
    options = { :query => {:status => text}, :basic_auth => @auth }
    HTTParty.post('http://www.twitter.com/statuses/update.json', options)
    

    And if you need to POST something in the body of the request, simply add :body => "text" to the options hash.

    It's very straightforward to work with and I'm currently using it in place of ActiveResource to consume some REST services from a Rails app.

    0 讨论(0)
  • 2021-02-04 21:43

    Simple answer, don't. I had a similar problem with ActiveResource, didn't like HTTParty's api (too many class methods), so I rolled my own. Try it out, it's called Wrest. It has partial support for Curl and deserialisation via REXML, LibXML, Nokogiri and JDom out of the box. You can trivially write your own deserialiser too.

    Here's an example for the Delicious api:

    class Delicious
      def initialize(options)
        @uri = "https://api.del.icio.us/v1/posts".to_uri(options)
      end
    
      def bookmarks(parameters = {})
        @uri['/get'].get(parameters)
      end
    
      def recent(parameters = {})
        @uri['/recent'].get(parameters)
      end
    
      def bookmark(parameters)
        @uri['/add'].post_form(parameters)
      end
    
      def delete(parameters)
        @uri['/delete'].delete(parameters)
      end
    end
    
    account = Delicious.new :username => 'kaiwren', :password => 'fupupp1es'
    account.bookmark(
        :url => 'http://blog.sidu.in/search/label/ruby',
        :description => 'The Ruby related posts on my blog!',
        :extended => "All posts tagged with 'ruby'",
        :tags => 'ruby hacking'
      )
    
    0 讨论(0)
提交回复
热议问题