Faraday: your new best friend

I am a die-hard REST API fan, however the default Net::HTTP Ruby lib is very verbose and doesn’t give me all the features and flexibility I need for coding API clients fast and easy.
Faraday is a hell of a tool.. (disclaimer: the name is not related with any English scientist well known for contributions in the electromagnetism field). Faraday it’s a HTTP library, started by Rick Olson, which reuses Rack middleware concepts and provides a common interface for building API wrappers. Also it supports many out of the box advanced features, like OAuth, SSL, HTTP caching (Last-Modified and ETag headers), HTTP proxy, easy response data parsing, which could be cumbersome to code and configure with the popular Net::HTTP lib.

Here is a basic snippet:

require 'faraday'

Faraday.get(:url => 'http://faradayisfun.com')

But you can code more complex things and tweak configurations:

require 'faraday'

conn = Faraday.new(:url => 'http://faradayisfun.com') do |builder|
  builder.response :logger #logging stuff
  builder.use Faraday::Adapter::NetHttp #default adapter for Net::HTTP
  builder.use FaradayMiddleware::ParseJson #cool for parsing response bodies
end

res = conn.post do |request|
  request.url '/example'
  request.headers['Content-Type'] = 'application/json'
  request.body = "{send: body}"
end

res.body

Do you need HTTP basic auth? Faraday gives you some:

...
conn.basic_auth('user', 'pwd')
...

With Faraday you can consume APIs with some lines of code and customize its behavior like a pro. Checkout the github repo and take a look at all the cool extra options and supported features.

Advertisements
Tagged , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: