Connecting to web services using Rails (HTTP requests)?

前端 未结 6 1680
终归单人心
终归单人心 2021-02-06 10:45

I am using Ruby on Rails 3 and I am trying to implement APIs to retrieve account information from a web service. That is, I would like to connect to a web service that has the A

相关标签:
6条回答
  • 2021-02-06 11:09

    If you don't need low-level tweak-ability offered by Net::HTTP, instead take a look at using Open-URI, which comes with Ruby. It makes it easy to request a page and receive the body back. Open-URI doesn't have all the bells and whistles but for a lot of what I do it's plenty good.

    A simple use looks like:

    require 'open-uri'
    body = open('http://www.example.com').read
    

    The docs have many other examples.

    These are other HTTP clients I like:

    • HTTPClient
    • Typhoeus

    They are more tweakable and can handle multiple connections at once if that's what you need. For instance, Typhoeus has a suite of simplified calls, similar to Open-URI's. From the docs:

    response = Typhoeus::Request.get("http://www.pauldix.net")
    response = Typhoeus::Request.head("http://www.pauldix.net")
    response = Typhoeus::Request.put("http://localhost:3000/posts/1", :body => "whoo, a body")
    response = Typhoeus::Request.post("http://localhost:3000/posts", :params => {:title => "test post", :content => "this is my test"})
    response = Typhoeus::Request.delete("http://localhost:3000/posts/1")
    

    HTTPClient has similar shortened methods too.

    0 讨论(0)
  • 2021-02-06 11:17

    rest-client is the most popular gem for easily connecting to RESTful web services

    0 讨论(0)
  • 2021-02-06 11:21

    Yes, since you're using RESTful routes, they are your basic API. You're also returning structured JSON data easily consumable by an application.

    There are other ways to implement a web services API (e.g. SOAP), but this is a good and proper way.

    Since it's a web services API, connecting to the correct URL and parsing the response is the way to go on the client side. Though if you need to access many different resources it might be a good idea to create a flexible way of building the request URL.

    0 讨论(0)
  • 2021-02-06 11:21

    I think one of the best solutions out there is the Her gem. It encapsulates restful requests providing objects with active-record like behavior.

    0 讨论(0)
  • 2021-02-06 11:29

    I'd recommend using Rails' ActiveResource for most cases. Failing that, httparty.

    0 讨论(0)
  • 2021-02-06 11:29

    I would use ActiveResource if you just need a simple way to pull in rest-based resources. It's already included in rails and pretty trivial to set up. You just specify a base url and resource name in your ActiveResource subclass and then you can CRUD rest-based resources with an interface similar to that of ActiveRecord.

    0 讨论(0)
提交回复
热议问题