- Notifications
You must be signed in to change notification settings - Fork995
Simple, but flexible HTTP client library, with support for multiple backends.
License
lostisland/faraday
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Faraday is an HTTP client lib that provides a common interface over manyadapters (such as Net::HTTP) and embraces the concept of Rack middleware whenprocessing the request/response cycle.
Faraday supports these adapters:
It also includes a Rack adapter for hitting loaded Rack applications throughRack::Test, and a Test adapter for stubbing requests by hand.
Available atrubydoc.info.
response=Faraday.get'http://sushi.com/nigiri/sake.json'
A simpleget
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 middlewarestack and default adapter (seeFaraday::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=Faraday.new(:url=>'http://www.example.com')response=conn.get'/users'# GET http://www.example.com/users'
Connections can also take an options hash as a parameter or be configured by using a block. Checkout the section calledAdvanced middleware usage for more details about how to use this block for configurations.Since the default middleware stack uses url_encoded middleware and default adapter, use them on building your own middleware stack.
conn=Faraday.new(:url=>'http://sushi.com')do |faraday|faraday.request:url_encoded# form-encode POST paramsfaraday.response:logger# log requests to STDOUTfaraday.adapterFaraday.default_adapter# make requests with Net::HTTPend# Filter sensitive information from logs with a regex matcherconn=Faraday.new(:url=>'http://sushi.com/api_key=s3cr3t')do |faraday|faraday.request:url_encoded# form-encode POST paramsfaraday.response:loggerdo |logger |logger.filter(/(api_key=)(\w+)/,'\1[REMOVED]')endfaraday.adapterFaraday.default_adapter# make requests with Net::HTTPend
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 http://sushi.com/nigiri/sake.jsonresponse.bodyconn.get'/nigiri',{:name=>'Maguro'}# GET http://sushi.com/nigiri?name=Maguroconn.getdo |req|# GET http://sushi.com/search?page=2&limit=100req.url'/search',:page=>2req.params['limit']=100end## POST ##conn.post'/nigiri',{:name=>'Maguro'}# POST "name=maguro" to http://sushi.com/nigiri
Some configuration options can be adjusted per request:
# post payload as JSON instead of "www-form-urlencoded" encoding:conn.postdo |req|req.url'/nigiri'req.headers['Content-Type']='application/json'req.body='{ "name": "Unagi" }'end## Per-request options ##conn.getdo |req|req.url'/search'req.options.timeout=5# open/read timeout in secondsreq.options.open_timeout=2# connection open timeout in secondsend
And you can inject arbitrary data into the request using thecontext
option:
# Anything you inject using context option will be available in the env on all middlewaresconn.getdo |req|req.url'/search'req.options.context={foo:'foo',bar:'bar'}end
Sometimes you need to send the same URL parameter multiple times with differentvalues. This requires manually setting the parameter encoder and can be done oneither per-connection or per-request basis.
# per-connection settingconn=Faraday.new:request=>{:params_encoder=>Faraday::FlatParamsEncoder}conn.getdo |req|# per-request setting:# req.options.params_encoder = my_encoderreq.params['roll']=['california','philadelphia']end# GET 'http://sushi.com?roll=california&roll=philadelphia'
The value of Faradayparams_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 bodiesget serialized. The default encoder is Faraday::NestedParamsEncoder.
Basic and Token authentication are handled by Faraday::Request::BasicAuthentication and Faraday::Request::TokenAuthentication respectively. These can be added as middleware manually or through the helper methods.
Faraday.new(...)do |conn|conn.basic_auth('username','password')endFaraday.new(...)do |conn|conn.token_auth('authentication-token')end
The order in which middleware is stacked is important. Like with Rack, thefirst middleware on the list wraps all others, while the last middleware is theinnermost one, so that must be the adapter.
Faraday.new(...)do |conn|# POST/PUT params encoders:conn.request:multipartconn.request:url_encoded# Last middleware must be the adapter:conn.adapter:net_httpend
This request middleware setup affects POST/PUT requests in the following way:
Request::Multipart
checks for files in the payload, otherwise leaveseverything untouched;Request::UrlEncoded
encodes as "application/x-www-form-urlencoded" if notalready encoded or of another type
Swapping middleware means giving the other priority. Specifying the"Content-Type" for the request is explicitly stating which middleware shouldprocess it.
Examples:
# uploading a file:payload[:profile_pic]=Faraday::UploadIO.new('/path/to/avatar.jpg','image/jpeg')# "Multipart" middleware detects files and encodes with "multipart/form-data":conn.put'/profile',payload
Middleware are classes that implement acall
instance method. They hook intothe request/response cycle.
defcall(request_env)# do something with the request# request_env[:request_headers].merge!(...)@app.call(request_env).on_completedo |response_env|# do something with the response# response_env[:response_headers].merge!(...)endend
It's important to do all processing of the response only in theon_complete
block. This enables middleware to work in parallel mode where requests areasynchronous.
Theenv
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:request_headers# response phase:status - HTTP response status code, such as 200:body - the response body:response_headers
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=Faraday.new(...)do |f|f.adapter:net_httpdo |http|# yields Net::HTTPhttp.idle_timeout=100http.verify_callback=lambdado |preverify_ok,cert_store |# do something here...endendend
conn=Faraday.new(...)do |f|f.adapter:net_http_persistentdo |http|# yields Net::HTTP::Persistenthttp.idle_timeout=100http.retry_change_requests=trueendend
conn=Faraday.new(...)do |f|f.adapter:patrondo |session|# yields Patron::Sessionsession.max_redirects=10endend
conn=Faraday.new(...)do |f|f.adapter:httpclientdo |client|# yields HTTPClientclient.keep_alive_timeout=20client.ssl_config.timeout=25endend
# It's possible to define stubbed request outside a test adapter block.stubs=Faraday::Adapter::Test::Stubs.newdo |stub|stub.get('/tamago'){ |env|[200,{},'egg']}end# You can pass stubbed request to the test adapter or define them in a block# or a combination of the two.test=Faraday.newdo |builder|builder.adapter:test,stubsdo |stub|stub.get('/ebi'){ |env|[200,{},'shrimp']}endend# 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.stubs.verify_stubbed_calls
This library aims to support and istested against the following Rubyimplementations:
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 Rubyimplementations, however support will only be provided for the versions listedabove.
If you would like this library to support another Ruby version, you mayvolunteer to be a maintainer. Being a maintainer entails making sure all testsrun and pass on that implementation. When something breaks on yourimplementation, you will be responsible for providing patches in a timelyfashion. If critical issues for a particular implementation exist at the timeof a major release, support for that Ruby version may be dropped.
Do you want to contribute to Faraday?Open the issues page and check for theany volunteer?
label!But before you start coding, please read ourContributing Guide
Copyright (c) 2009-2017Rick Olson, Zack Hobson.SeeLICENSE for details.
About
Simple, but flexible HTTP client library, with support for multiple backends.
Resources
License
Code of conduct
Uh oh!
There was an error while loading.Please reload this page.