318 lines (245 sloc) 9.74 KB


Faraday is an HTTP client lib that provides a common interface over many adapters (such as Net::HTTP) and embraces the concept of Rack middleware when processing the request/response cycle.

Faraday supports these adapters:

It also includes a Rack adapter for hitting loaded Rack applications through Rack::Test, and a Test adapter for stubbing requests by hand.

API documentation

Available at


Basic Use

response = Faraday.get ''

A simple get request can be performed by using the syntax described above. This works if you don't need to set up anything; you can roll with just the default middleware stack and default adapter (see Faraday::RackBuilder#initialize).

A more flexible way to use Faraday is to start with a Connection object. If you want to keep the same defaults, you can use this syntax:

conn = => '') 
response = conn.get '/users'                 # GET' 

Connections can also take an options hash as a parameter or be configured by using a block. Checkout the section called Advanced middleware usage for more details about how to use this block for configurations.

conn = => '') do |faraday|
  faraday.request  :url_encoded             # form-encode POST params
  faraday.response :logger                  # log requests to STDOUT
  faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP

# Filter sensitive information from logs with a regex matcher

conn = => '') do |faraday|
  faraday.response :logger do | logger |

Once you have the connection object, use it to make HTTP requests. You can pass paramters to it in a few different ways:

## GET ##

response = conn.get '/nigiri/sake.json'     # GET

conn.get '/nigiri', { :name => 'Maguro' }   # GET

conn.get do |req|                           # GET  
  req.url '/search', :page => 2
  req.params['limit'] = 100

## POST ## '/nigiri', { :name => 'Maguro' }  # POST "name=maguro" to

Some configuration options can be adjusted per request:

# post payload as JSON instead of "www-form-urlencoded" encoding: do |req|
  req.url '/nigiri'
  req.headers['Content-Type'] = 'application/json'
  req.body = '{ "name": "Unagi" }'

## Per-request options ##

conn.get do |req|
  req.url '/search'
  req.options.timeout = 5           # open/read timeout in seconds
  req.options.open_timeout = 2      # connection open timeout in seconds

Changing how parameters are serialized

Sometimes you need to send the same URL parameter multiple times with different values. This requires manually setting the parameter encoder and can be done on either per-connection or per-request basis.

# per-connection setting
conn = :request => { :params_encoder => Faraday::FlatParamsEncoder }

conn.get do |req|
  # per-request setting:
  # req.options.params_encoder = my_encoder
  req.params['roll'] = ['california', 'philadelphia']
# GET ''

The value of Faraday params_encoder can be any object that responds to:

  • encode(hash) #=> String
  • decode(string) #=> Hash

The encoder will affect both how query strings are processed and how POST bodies get serialized. The default encoder is Faraday::NestedParamsEncoder.

Advanced middleware usage

The order in which middleware is stacked is important. Like with Rack, the first middleware on the list wraps all others, while the last middleware is the innermost one, so that must be the adapter. do |conn|
  # POST/PUT params encoders:
  conn.request :multipart
  conn.request :url_encoded

  conn.adapter :net_http

This request middleware setup affects POST/PUT requests in the following way:

  1. Request::Multipart checks for files in the payload, otherwise leaves everything untouched;
  2. Request::UrlEncoded encodes as "application/x-www-form-urlencoded" if not already encoded or of another type

Swapping middleware means giving the other priority. Specifying the "Content-Type" for the request is explicitly stating which middleware should process it.


# uploading a file:
payload[:profile_pic] ='/path/to/avatar.jpg', 'image/jpeg')

# "Multipart" middleware detects files and encodes with "multipart/form-data":
conn.put '/profile', payload

Writing middleware

Middleware are classes that implement a call instance method. They hook into the request/response cycle.

def call(request_env)
  # do something with the request
  # request_env[:request_headers].merge!(...) do |response_env|
    # do something with the response
    # response_env[:response_headers].merge!(...)

It's important to do all processing of the response only in the on_complete block. This enables middleware to work in parallel mode where requests are asynchronous.

The env is a hash with symbol keys that contains info about the request and, later, response. Some keys are:

# request phase
:method - :get, :post, ...
:url    - URI for the current request; also contains GET parameters
:body   - POST parameters for :post/:put requests

# response phase
:status - HTTP response status code, such as 200
:body   - the response body

Ad-hoc adapters customization

Faraday is intended to be a generic interface between your code and the adapter. However, sometimes you need to access a feature specific to one of the adapters that is not covered in Faraday's interface.

When that happens, you can pass a block when specifying the adapter to customize it. The block parameter will change based on the adapter you're using. See below for some examples.


conn = do |f|
  f.adapter :net_http do |http| # yields Net::HTTP
    http.idle_timeout = 100
    http.verify_callback = lambda do | preverify_ok, cert_store |
      # do something here...


conn = do |f|
  f.adapter :net_http_persistent do |http| # yields Net::HTTP::Persistent
    http.idle_timeout = 100
    http.retry_change_requests = true


conn = do |f|
  f.adapter :patron do |session| # yields Patron::Session
    session.max_redirects = 10


conn = do |f|
  f.adapter :httpclient do |client| # yields HTTPClient
    client.keep_alive_timeout = 20
    client.ssl_config.timeout = 25

Using Faraday for testing

# It's possible to define stubbed request outside a test adapter block.
stubs = do |stub|
  stub.get('/tamago') { |env| [200, {}, 'egg'] }

# You can pass stubbed request to the test adapter or define them in a block
# or a combination of the two.
test = do |builder|
  builder.adapter :test, stubs do |stub|
    stub.get('/ebi') { |env| [ 200, {}, 'shrimp' ]}

# It's also possible to stub additional requests after the connection has
# been initialized. This is useful for testing.
stubs.get('/uni') { |env| [ 200, {}, 'urchin' ]}

resp = test.get '/tamago'
resp.body # => 'egg'
resp = test.get '/ebi'
resp.body # => 'shrimp'
resp = test.get '/uni'
resp.body # => 'urchin'
resp = test.get '/else' #=> raises "no such stub" error

# If you like, you can treat your stubs as mocks by verifying that all of
# the stubbed calls were made. NOTE that this feature is still fairly
# experimental: It will not verify the order or count of any stub, only that
# it was called once during the course of the test.


  • support streaming requests/responses
  • better stubbing API

Supported Ruby versions

This library aims to support and is tested against the following Ruby implementations:

If something doesn't work on one of these Ruby versions, it's a bug.

This library may inadvertently work (or seem to work) on other Ruby implementations, however support will only be provided for the versions listed above.

If you would like this library to support another Ruby version, you may volunteer to be a maintainer. Being a maintainer entails making sure all tests run and pass on that implementation. When something breaks on your implementation, you will be responsible for providing patches in a timely fashion. If critical issues for a particular implementation exist at the time of a major release, support for that Ruby version may be dropped.


Copyright (c) 2009-2013 Rick Olson, Zack Hobson. See LICENSE for details.