mirror of
https://github.com/lostisland/faraday.git
synced 2025-12-07 00:01:45 -05:00
merge readme changes
This commit is contained in:
commit
a928ee53ad
204
README.md
204
README.md
@ -5,61 +5,83 @@ Modular HTTP client library that uses middleware. Heavily inspired by Rack.
|
|||||||
[gemnasium]: https://gemnasium.com/technoweenie/faraday
|
[gemnasium]: https://gemnasium.com/technoweenie/faraday
|
||||||
|
|
||||||
## <a name="usage"></a>Usage
|
## <a name="usage"></a>Usage
|
||||||
conn = Faraday.new(:url => 'http://sushi.com') do |builder|
|
|
||||||
builder.use Faraday::Request::UrlEncoded # convert request params as "www-form-urlencoded"
|
|
||||||
builder.use Faraday::Request::JSON # encode request params as json
|
|
||||||
builder.use Faraday::Response::Logger # log the request to STDOUT
|
|
||||||
builder.use Faraday::Adapter::NetHttp # make http requests with Net::HTTP
|
|
||||||
|
|
||||||
# or, use shortcuts:
|
```ruby
|
||||||
builder.request :url_encoded
|
conn = Faraday.new(:url => 'http://sushi.com') do |builder|
|
||||||
builder.request :json
|
builder.use Faraday::Request::UrlEncoded # convert request params as "www-form-urlencoded"
|
||||||
builder.response :logger
|
builder.use Faraday::Request::JSON # encode request params as json
|
||||||
builder.adapter :net_http
|
builder.use Faraday::Response::Logger # log the request to STDOUT
|
||||||
end
|
builder.use Faraday::Adapter::NetHttp # make http requests with Net::HTTP
|
||||||
|
|
||||||
## GET ##
|
# or, use shortcuts:
|
||||||
|
builder.request :url_encoded
|
||||||
|
builder.request :json
|
||||||
|
builder.response :logger
|
||||||
|
builder.adapter :net_http
|
||||||
|
end
|
||||||
|
|
||||||
response = conn.get '/nigiri/sake.json' # GET http://sushi.com/nigiri/sake.json
|
## GET ##
|
||||||
response.body
|
|
||||||
|
|
||||||
conn.get '/nigiri', 'X-Awesome' => true # custom request header
|
response = conn.get '/nigiri/sake.json' # GET http://sushi.com/nigiri/sake.json
|
||||||
|
response.body
|
||||||
|
|
||||||
conn.get do |req| # GET http://sushi.com/search?page=2&limit=100
|
conn.get '/nigiri', 'X-Awesome' => true # custom request header
|
||||||
req.url '/search', :page => 2
|
|
||||||
req.params['limit'] = 100
|
|
||||||
end
|
|
||||||
|
|
||||||
## POST ##
|
conn.get do |req| # GET http://sushi.com/search?page=2&limit=100
|
||||||
|
req.url '/search', :page => 2
|
||||||
|
req.params['limit'] = 100
|
||||||
|
end
|
||||||
|
|
||||||
conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri
|
## POST ##
|
||||||
|
|
||||||
# post payload as JSON instead of "www-form-urlencoded" encoding:
|
conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri
|
||||||
conn.post '/nigiri', payload, 'Content-Type' => 'application/json'
|
|
||||||
|
|
||||||
# a more verbose way:
|
# post payload as JSON instead of "www-form-urlencoded" encoding:
|
||||||
conn.post do |req|
|
conn.post '/nigiri', payload, 'Content-Type' => 'application/json'
|
||||||
req.url '/nigiri'
|
|
||||||
req.headers['Content-Type'] = 'application/json'
|
# a more verbose way:
|
||||||
req.body = { :name => 'Unagi' }
|
conn.post do |req|
|
||||||
end
|
req.url '/nigiri'
|
||||||
|
req.headers['Content-Type'] = 'application/json'
|
||||||
|
req.body = { :name => 'Unagi' }
|
||||||
|
end
|
||||||
|
|
||||||
|
## Options ##
|
||||||
|
|
||||||
|
conn.get do |req|
|
||||||
|
req.url '/search'
|
||||||
|
req.options = {
|
||||||
|
:timeout => 5, # open/read timeout Integer in seconds
|
||||||
|
:open_timeout => 2, # read timeout Integer in seconds
|
||||||
|
:proxy => {
|
||||||
|
:uri => "http://example.org/", # proxy server URI
|
||||||
|
:user => "me", # proxy server username
|
||||||
|
:password => "test123" # proxy server password
|
||||||
|
}
|
||||||
|
}
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
If you're ready to roll with just the bare minimum:
|
If you're ready to roll with just the bare minimum:
|
||||||
|
|
||||||
# default stack (net/http), no extra middleware:
|
```ruby
|
||||||
response = Faraday.get 'http://sushi.com/nigiri/sake.json'
|
# default stack (net/http), no extra middleware:
|
||||||
|
response = Faraday.get 'http://sushi.com/nigiri/sake.json'
|
||||||
|
```
|
||||||
|
|
||||||
## Advanced middleware usage
|
## 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's usually the adapter.
|
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's usually the adapter.
|
||||||
|
|
||||||
conn = Faraday.new(:url => 'http://sushi.com') do |builder|
|
```ruby
|
||||||
# POST/PUT params encoders:
|
conn = Faraday.new(:url => 'http://sushi.com') do |builder|
|
||||||
builder.request :multipart
|
# POST/PUT params encoders:
|
||||||
builder.request :url_encoded
|
builder.request :multipart
|
||||||
builder.request :json
|
builder.request :url_encoded
|
||||||
|
builder.request :json
|
||||||
|
|
||||||
builder.adapter :net_http
|
builder.adapter :net_http
|
||||||
end
|
end
|
||||||
|
```
|
||||||
|
|
||||||
This request middleware setup affects POST/PUT requests in the following way:
|
This request middleware setup affects POST/PUT requests in the following way:
|
||||||
|
|
||||||
@ -71,79 +93,87 @@ Because "UrlEncoded" is higher on the stack than JSON encoder, it will get to pr
|
|||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
|
|
||||||
payload = { :name => 'Maguro' }
|
```ruby
|
||||||
|
payload = { :name => 'Maguro' }
|
||||||
|
|
||||||
# post payload as JSON instead of urlencoded:
|
# post payload as JSON instead of urlencoded:
|
||||||
conn.post '/nigiri', payload, 'Content-Type' => 'application/json'
|
conn.post '/nigiri', payload, 'Content-Type' => 'application/json'
|
||||||
|
|
||||||
# uploading a file:
|
# uploading a file:
|
||||||
payload = { :profile_pic => Faraday::UploadIO.new('avatar.jpg', 'image/jpeg') }
|
payload = { :profile_pic => Faraday::UploadIO.new('avatar.jpg', 'image/jpeg') }
|
||||||
|
|
||||||
# "Multipart" middleware detects files and encodes with "multipart/form-data":
|
# "Multipart" middleware detects files and encodes with "multipart/form-data":
|
||||||
conn.put '/profile', payload
|
conn.put '/profile', payload
|
||||||
|
```
|
||||||
|
|
||||||
## Writing middleware
|
## Writing middleware
|
||||||
Middleware are classes that respond to `call()`. They wrap the request/response cycle.
|
Middleware are classes that respond to `call()`. They wrap the request/response cycle.
|
||||||
|
|
||||||
def call(env)
|
```ruby
|
||||||
# do something with the request
|
def call(env)
|
||||||
|
# do something with the request
|
||||||
|
|
||||||
@app.call(env).on_complete do
|
@app.call(env).on_complete do
|
||||||
# do something with the response
|
# do something with the response
|
||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
```
|
||||||
|
|
||||||
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.
|
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:
|
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, ...
|
# request phase
|
||||||
:url - URI for the current request; also contains GET parameters
|
:method - :get, :post, ...
|
||||||
:body - POST parameters for :post/:put requests
|
:url - URI for the current request; also contains GET parameters
|
||||||
:request_headers
|
:body - POST parameters for :post/:put requests
|
||||||
|
:request_headers
|
||||||
|
|
||||||
# response phase
|
# response phase
|
||||||
:status - HTTP response status code, such as 200
|
:status - HTTP response status code, such as 200
|
||||||
:body - the response body
|
:body - the response body
|
||||||
:response_headers
|
:response_headers
|
||||||
|
```
|
||||||
|
|
||||||
## <a name="testing"></a>Testing
|
## <a name="testing"></a>Testing
|
||||||
# It's possible to define stubbed request outside a test adapter block.
|
|
||||||
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
|
|
||||||
stub.get('/tamago') { [200, {}, 'egg'] }
|
|
||||||
end
|
|
||||||
|
|
||||||
# You can pass stubbed request to the test adapter or define them in a block
|
```ruby
|
||||||
# or a combination of the two.
|
# It's possible to define stubbed request outside a test adapter block.
|
||||||
test = Faraday.new do |builder|
|
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
|
||||||
builder.adapter :test, stubs do |stub|
|
stub.get('/tamago') { [200, {}, 'egg'] }
|
||||||
stub.get('/ebi') {[ 200, {}, 'shrimp' ]}
|
end
|
||||||
end
|
|
||||||
end
|
|
||||||
|
|
||||||
# It's also possible to stub additional requests after the connection has
|
# You can pass stubbed request to the test adapter or define them in a block
|
||||||
# been initialized. This is useful for testing.
|
# or a combination of the two.
|
||||||
stubs.get('/uni') {[ 200, {}, 'urchin' ]}
|
test = Faraday.new do |builder|
|
||||||
|
builder.adapter :test, stubs do |stub|
|
||||||
|
stub.get('/ebi') {[ 200, {}, 'shrimp' ]}
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
resp = test.get '/tamago'
|
# It's also possible to stub additional requests after the connection has
|
||||||
resp.body # => 'egg'
|
# been initialized. This is useful for testing.
|
||||||
resp = test.get '/ebi'
|
stubs.get('/uni') {[ 200, {}, 'urchin' ]}
|
||||||
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
|
resp = test.get '/tamago'
|
||||||
# the stubbed calls were made. NOTE that this feature is still fairly
|
resp.body # => 'egg'
|
||||||
# experimental: It will not verify the order or count of any stub, only that
|
resp = test.get '/ebi'
|
||||||
# it was called once during the course of the test.
|
resp.body # => 'shrimp'
|
||||||
stubs.verify_stubbed_calls
|
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.
|
||||||
|
stubs.verify_stubbed_calls
|
||||||
|
```
|
||||||
|
|
||||||
## <a name="todo"></a>TODO
|
## <a name="todo"></a>TODO
|
||||||
* support streaming requests/responses
|
* support streaming requests/responses
|
||||||
* better stubbing API
|
* better stubbing API
|
||||||
* Support timeouts
|
|
||||||
* Add curb, em-http, fast_http
|
* Add curb, em-http, fast_http
|
||||||
|
|
||||||
## <a name="pulls"></a>Note on Patches/Pull Requests
|
## <a name="pulls"></a>Note on Patches/Pull Requests
|
||||||
|
|||||||
@ -15,12 +15,16 @@ module Faraday
|
|||||||
autoload_all 'faraday/request',
|
autoload_all 'faraday/request',
|
||||||
:JSON => 'json',
|
:JSON => 'json',
|
||||||
:UrlEncoded => 'url_encoded',
|
:UrlEncoded => 'url_encoded',
|
||||||
:Multipart => 'multipart'
|
:Multipart => 'multipart',
|
||||||
|
:Retry => 'retry',
|
||||||
|
:Timeout => 'timeout'
|
||||||
|
|
||||||
register_lookup_modules \
|
register_lookup_modules \
|
||||||
:json => :JSON,
|
:json => :JSON,
|
||||||
:url_encoded => :UrlEncoded,
|
:url_encoded => :UrlEncoded,
|
||||||
:multipart => :Multipart
|
:multipart => :Multipart,
|
||||||
|
:retry => :Retry,
|
||||||
|
:timeout => :Timeout
|
||||||
|
|
||||||
attr_reader :method
|
attr_reader :method
|
||||||
|
|
||||||
|
|||||||
21
lib/faraday/request/retry.rb
Normal file
21
lib/faraday/request/retry.rb
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
module Faraday
|
||||||
|
class Request::Retry < Faraday::Middleware
|
||||||
|
def initialize(app, retries = 2)
|
||||||
|
@retries = retries
|
||||||
|
super(app)
|
||||||
|
end
|
||||||
|
|
||||||
|
def call(env)
|
||||||
|
retries = @retries
|
||||||
|
begin
|
||||||
|
@app.call(env)
|
||||||
|
rescue StandardError, Timeout::Error => e
|
||||||
|
if retries > 0
|
||||||
|
retries -= 1
|
||||||
|
retry
|
||||||
|
end
|
||||||
|
raise
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
31
lib/faraday/request/timeout.rb
Normal file
31
lib/faraday/request/timeout.rb
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
module Faraday
|
||||||
|
class Request::Timeout < Faraday::Middleware
|
||||||
|
dependency "timeout"
|
||||||
|
|
||||||
|
def initialize(app, timeout = 2)
|
||||||
|
self.class.dependency "system_timer" if ruby18?
|
||||||
|
@timeout = timeout
|
||||||
|
super(app)
|
||||||
|
end
|
||||||
|
|
||||||
|
def call(env)
|
||||||
|
method =
|
||||||
|
if ruby18? && self.class.loaded?
|
||||||
|
SystemTimer.method(:timeout_after)
|
||||||
|
else
|
||||||
|
Timeout.method(:timeout)
|
||||||
|
end
|
||||||
|
|
||||||
|
method.call(@timeout) do
|
||||||
|
@app.call(env)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def ruby18?
|
||||||
|
@ruby18 ||= RUBY_VERSION =~ /^1\.8/
|
||||||
|
end
|
||||||
|
|
||||||
|
end
|
||||||
|
end
|
||||||
25
test/middleware/retry_test.rb
Normal file
25
test/middleware/retry_test.rb
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
require File.expand_path(File.join(File.dirname(__FILE__), "..", "helper"))
|
||||||
|
|
||||||
|
module Middleware
|
||||||
|
class RetryTest < Faraday::TestCase
|
||||||
|
def setup
|
||||||
|
@stubs = Faraday::Adapter::Test::Stubs.new
|
||||||
|
@conn = Faraday.new do |b|
|
||||||
|
b.request :retry, 2
|
||||||
|
b.adapter :test, @stubs
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_retries
|
||||||
|
times_called = 0
|
||||||
|
|
||||||
|
@stubs.post("/echo") do
|
||||||
|
times_called += 1
|
||||||
|
raise "Error occurred"
|
||||||
|
end
|
||||||
|
|
||||||
|
@conn.post("/echo") rescue nil
|
||||||
|
assert_equal times_called, 3
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
20
test/middleware/timeout_test.rb
Normal file
20
test/middleware/timeout_test.rb
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
require File.expand_path(File.join(File.dirname(__FILE__), "..", "helper"))
|
||||||
|
|
||||||
|
module Middleware
|
||||||
|
class TimeoutTest < Faraday::TestCase
|
||||||
|
def setup
|
||||||
|
@conn = Faraday.new do |b|
|
||||||
|
b.request :timeout, 0.01 # 10 ms
|
||||||
|
b.adapter :test do |stub|
|
||||||
|
stub.post("/echo") do |env|
|
||||||
|
sleep(1)
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
def test_request_times_out
|
||||||
|
assert_raise(TimeoutError) { @conn.post("/echo") }
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
Loading…
x
Reference in New Issue
Block a user