When we want to integrate a new cloud service or social network, we’re often fortunate enough to find a library (in the form of a gem) which wraps their API. Sometimes the wrapper is very complex and full-featured, other times it’s relatively barebones. Other times we need to interact directly with the HTTP APIs.
We’ve found that the most comfortable way to wrap HTTP APIs is to use Faraday as an HTTP connection manager. It’s more comfortable for a number of reasons, but mostly because of swappable middleware and swappable adapters. We can add any kind of behavior to the connection (logging, exception tracing, transformation) without touching the main application code. We can add stubbed responses, and the whole middleware stack will be executed as if they were coming from the actual servers.
One exception has been the official SoundCloud library (available here). The gem is actually a very thin wrapper around HTTParty, adding token authentication and a number of predefined operation to exchange credentials. Because of this approach, using the SoundCloud gem means that we had to build all HTTP paths by hand. Rather than following this approach, we decided to build a new library from scratch with the following requirements:
1) The library should explicitly declare methods for all the available endpoints, effectively hiding that there is any HTTP involved.
2) The library should use Faraday as its connection manager, which allows for much simpler configuration (e.g. using MultiJson for deserialization, checking for HTTP status codes, etc.)
Because we chose to use Faraday, you can swap the adapter:
1) to be used inside an EventMachine reactor loop (by configuring Faraday to use the corresponding :em-http adapter, attaching callbacks to the response itself)
2) to handle persistent connections and parallel requests
3) to add/modify the behavior of the library (by confi“guring the default middleware stack)
You can find the gem and a lot of documentation here, and use in your Rails app by adding the following line to your Gemfile:
Let us know if you find this library useful, as well as any other feedback you may have!`