Class: Faraday::Connection

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/faraday/connection.rb

Overview

Connection objects manage the default properties and the middleware stack for fulfilling an HTTP request.

Examples:


conn = Faraday::Connection.new 'http://sushi.com'

# GET http://sushi.com/nigiri
conn.get 'nigiri'
# => #<Faraday::Response>

Constant Summary collapse

METHODS =

A Set of allowed HTTP verbs.

Set.new %i[get post put delete head patch options trace connect]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url = nil, options = nil) {|self| ... } ⇒ Connection

Initializes a new Faraday::Connection.

Parameters:

  • url (URI, String) (defaults to: nil)

    URI or String base URL to use as a prefix for all requests (optional).

  • options (Hash, Faraday::ConnectionOptions) (defaults to: nil)

Options Hash (options):

  • :url (URI, String) — default: 'http:/'

    URI or String base URL

  • :params (Hash<String => String>)

    URI query unencoded key/value pairs.

  • :headers (Hash<String => String>)

    Hash of unencoded HTTP header key/value pairs.

  • :request (Hash)

    Hash of request options.

  • :ssl (Hash)

    Hash of SSL options.

  • :proxy (Hash, URI, String)

    proxy options, either as a URL or as a Hash

  • :proxy[:uri] (URI, String)
  • :proxy[:user] (String)
  • :proxy[:password] (String)

Yields:

  • (self)

    after all setup has been done



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/faraday/connection.rb', line 62

def initialize(url = nil, options = nil)
  options = ConnectionOptions.from(options)

  if url.is_a?(Hash) || url.is_a?(ConnectionOptions)
    options = options.merge(url)
    url     = options.url
  end

  @parallel_manager = nil
  @headers = Utils::Headers.new
  @params  = Utils::ParamsHash.new
  @options = options.request
  @ssl = options.ssl
  @default_parallel_manager = options.parallel_manager

  @builder = options.builder || begin
    # pass an empty block to Builder so it doesn't assume default middleware
    options.new_builder(block_given? ? proc { |b| } : nil)
  end

  self.url_prefix = url || 'http:/'

  @params.update(options.params)   if options.params
  @headers.update(options.headers) if options.headers

  initialize_proxy(url, options)

  yield(self) if block_given?

  @headers[:user_agent] ||= "Faraday v#{VERSION}"
end

Instance Attribute Details

#builderFaraday::Builder (readonly)

Returns Builder for this Connection.

Returns:

  • (Faraday::Builder)

    Builder for this Connection.



30
31
32
# File 'lib/faraday/connection.rb', line 30

def builder
  @builder
end

#default_parallel_manager { ... } ⇒ Object?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Check if the adapter is parallel-capable.

Yields:

  • if the adapter isn’t parallel-capable, or if no adapter is set yet.

Returns:

  • (Object, nil)

    a parallel manager or nil if yielded



355
356
357
358
359
360
361
362
363
364
365
# File 'lib/faraday/connection.rb', line 355

def default_parallel_manager
  @default_parallel_manager ||= begin
    adapter = @builder.adapter.klass if @builder.adapter

    if support_parallel?(adapter)
      adapter.setup_parallel_manager
    elsif block_given?
      yield
    end
  end
end

#headersHash

Returns unencoded HTTP header key/value pairs.

Returns:

  • (Hash)

    unencoded HTTP header key/value pairs.



23
24
25
# File 'lib/faraday/connection.rb', line 23

def headers
  @headers
end

#parallel_managerObject (readonly)

Returns the parallel manager for this Connection.

Returns:

  • (Object)

    the parallel manager for this Connection.



36
37
38
# File 'lib/faraday/connection.rb', line 36

def parallel_manager
  @parallel_manager
end

#paramsHash

Returns URI query unencoded key/value pairs.

Returns:

  • (Hash)

    URI query unencoded key/value pairs.



20
21
22
# File 'lib/faraday/connection.rb', line 20

def params
  @params
end

#proxyHash

Returns proxy options.

Returns:

  • (Hash)

    proxy options.



42
43
44
# File 'lib/faraday/connection.rb', line 42

def proxy
  @proxy
end

#sslHash (readonly)

Returns SSL options.

Returns:

  • (Hash)

    SSL options.



33
34
35
# File 'lib/faraday/connection.rb', line 33

def ssl
  @ssl
end

#url_prefixString

Returns a URI with the prefix used for all requests from this Connection. This includes a default host name, scheme, port, and path.

Returns:

  • (String)

    a URI with the prefix used for all requests from this Connection. This includes a default host name, scheme, port, and path.



27
28
29
# File 'lib/faraday/connection.rb', line 27

def url_prefix
  @url_prefix
end

Class Method Details

.connect(url = nil, params = nil, headers = nil) {|Faraday::Request| ... } ⇒ Faraday::Response

Makes a CONNECT HTTP request without a body.

Examples:

conn.connect '/items/1'

Parameters:

  • url (String) (defaults to: nil)

    The optional String base URL to use as a prefix for all requests. Can also be the options Hash.

  • params (Hash) (defaults to: nil)

    Hash of URI query unencoded key/value pairs.

  • headers (Hash) (defaults to: nil)

    unencoded HTTP header key/value pairs.

Yields:

Returns:



# File 'lib/faraday/connection.rb', line 173

.delete(url = nil, params = nil, headers = nil) {|Faraday::Request| ... } ⇒ Faraday::Response

Makes a DELETE HTTP request without a body.

Examples:

conn.delete '/items/1'

Parameters:

  • url (String) (defaults to: nil)

    The optional String base URL to use as a prefix for all requests. Can also be the options Hash.

  • params (Hash) (defaults to: nil)

    Hash of URI query unencoded key/value pairs.

  • headers (Hash) (defaults to: nil)

    unencoded HTTP header key/value pairs.

Yields:

Returns:



# File 'lib/faraday/connection.rb', line 158

.get(url = nil, params = nil, headers = nil) {|Faraday::Request| ... } ⇒ Faraday::Response

Makes a GET HTTP request without a body.

Examples:

conn.get '/items', { page: 1 }, :accept => 'application/json'

# ElasticSearch example sending a body with GET.
conn.get '/twitter/tweet/_search' do |req|
  req.headers[:content_type] = 'application/json'
  req.params[:routing] = 'kimchy'
  req.body = JSON.generate(query: {...})
end

Parameters:

  • url (String) (defaults to: nil)

    The optional String base URL to use as a prefix for all requests. Can also be the options Hash.

  • params (Hash) (defaults to: nil)

    Hash of URI query unencoded key/value pairs.

  • headers (Hash) (defaults to: nil)

    unencoded HTTP header key/value pairs.

Yields:

Returns:



# File 'lib/faraday/connection.rb', line 121

.head(url = nil, params = nil, headers = nil) {|Faraday::Request| ... } ⇒ Faraday::Response

Makes a HEAD HTTP request without a body.

Examples:

conn.head '/items/1'

Parameters:

  • url (String) (defaults to: nil)

    The optional String base URL to use as a prefix for all requests. Can also be the options Hash.

  • params (Hash) (defaults to: nil)

    Hash of URI query unencoded key/value pairs.

  • headers (Hash) (defaults to: nil)

    unencoded HTTP header key/value pairs.

Yields:

Returns:



# File 'lib/faraday/connection.rb', line 143

.post(url = nil, body = nil, headers = nil) {|Faraday::Request| ... } ⇒ Faraday::Response

Makes a POST HTTP request with a body.

Examples:

conn.post '/items', data, content_type: 'application/json'

# Simple ElasticSearch indexing sample.
conn.post '/twitter/tweet' do |req|
  req.headers[:content_type] = 'application/json'
  req.params[:routing] = 'kimchy'
  req.body = JSON.generate(user: 'kimchy', ...)
end

Parameters:

  • url (String) (defaults to: nil)

    The optional String base URL to use as a prefix for all requests. Can also be the options Hash.

  • body (String) (defaults to: nil)

    body for the request.

  • headers (Hash) (defaults to: nil)

    unencoded HTTP header key/value pairs.

Yields:

Returns:



# File 'lib/faraday/connection.rb', line 239

.put(url = nil, body = nil, headers = nil) {|Faraday::Request| ... } ⇒ Faraday::Response

Makes a PUT HTTP request with a body.

Examples:

# TODO: Make it a PUT example
conn.post '/items', data, content_type: 'application/json'

# Simple ElasticSearch indexing sample.
conn.post '/twitter/tweet' do |req|
  req.headers[:content_type] = 'application/json'
  req.params[:routing] = 'kimchy'
  req.body = JSON.generate(user: 'kimchy', ...)
end

Parameters:

  • url (String) (defaults to: nil)

    The optional String base URL to use as a prefix for all requests. Can also be the options Hash.

  • body (String) (defaults to: nil)

    body for the request.

  • headers (Hash) (defaults to: nil)

    unencoded HTTP header key/value pairs.

Yields:

Returns:



# File 'lib/faraday/connection.rb', line 261

.trace(url = nil, params = nil, headers = nil) {|Faraday::Request| ... } ⇒ Faraday::Response

Makes a TRACE HTTP request without a body.

Examples:

conn.connect '/items/1'

Parameters:

  • url (String) (defaults to: nil)

    The optional String base URL to use as a prefix for all requests. Can also be the options Hash.

  • params (Hash) (defaults to: nil)

    Hash of URI query unencoded key/value pairs.

  • headers (Hash) (defaults to: nil)

    unencoded HTTP header key/value pairs.

Yields:

Returns:



# File 'lib/faraday/connection.rb', line 188

Instance Method Details

#authorization(type, token) ⇒ void

This method returns an undefined value.

Sets up a custom Authorization header.

Examples:


conn.authorization :Bearer, 'mF_9.B5f-4.1JqM'
conn.headers['Authorization']
# => "Bearer mF_9.B5f-4.1JqM"

conn.authorization :Token, token: 'abcdef', foo: 'bar'
conn.headers['Authorization']
# => "Token token=\"abcdef\",
            foo=\"bar\""

Parameters:

  • type (String)

    authorization type

  • token (String, Hash)

    token. A String value is taken literally, and a Hash is encoded into comma-separated key/value pairs.



345
346
347
# File 'lib/faraday/connection.rb', line 345

def authorization(type, token)
  set_authorization_header(:authorization, type, token)
end

#basic_auth(login, pass) ⇒ void

This method returns an undefined value.

Sets up the Authorization header with these credentials, encoded with base64.

Examples:


conn.basic_auth 'Aladdin', 'open sesame'
conn.headers['Authorization']
# => "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

Parameters:

  • login (String)

    The authentication login.

  • pass (String)

    The authentication password.



306
307
308
# File 'lib/faraday/connection.rb', line 306

def basic_auth(, pass)
  set_authorization_header(:basic_auth, , pass)
end

#build_exclusive_url(url = nil, params = nil, params_encoder = nil) ⇒ URI

Build an absolute URL based on url_prefix.

of the resulting url (default: nil).

Parameters:

  • url (String, URI) (defaults to: nil)
  • params (Faraday::Utils::ParamsHash) (defaults to: nil)

    A Faraday::Utils::ParamsHash to replace the query values

Returns:

  • (URI)


530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/faraday/connection.rb', line 530

def build_exclusive_url(url = nil, params = nil, params_encoder = nil)
  url = nil if url.respond_to?(:empty?) && url.empty?
  base = url_prefix
  if url && base.path && base.path !~ %r{/$}
    base = base.dup
    base.path = base.path + '/' # ensure trailing slash
  end
  uri = url ? base + url : base
  if params
    uri.query = params.to_query(params_encoder || options.params_encoder)
  end
  # rubocop:disable Style/SafeNavigation
  uri.query = nil if uri.query && uri.query.empty?
  # rubocop:enable Style/SafeNavigation
  uri
end

#build_request(method) {|Faraday::Request| ... } ⇒ Faraday::Request

Creates and configures the request object.

Parameters:

  • method (Symbol)

Yields:

Returns:



513
514
515
516
517
518
519
520
# File 'lib/faraday/connection.rb', line 513

def build_request(method)
  Request.create(method) do |req|
    req.params  = params.dup
    req.headers = headers.dup
    req.options = options
    yield(req) if block_given?
  end
end

#build_url(url = nil, extra_params = nil) ⇒ Object

Takes a relative url for a request and combines it with the defaults set on the connection instance.

Examples:

conn = Faraday::Connection.new { ... }
conn.url_prefix = "https://sushi.com/api?token=abc"
conn.scheme      # => https
conn.path_prefix # => "/api"

conn.build_url("nigiri?page=2")
# => https://sushi.com/api/nigiri?token=abc&page=2

conn.build_url("nigiri", page: 2)
# => https://sushi.com/api/nigiri?token=abc&page=2

Parameters:

  • url (String) (defaults to: nil)
  • extra_params (Hash) (defaults to: nil)


464
465
466
467
468
469
470
471
472
473
474
475
476
477
# File 'lib/faraday/connection.rb', line 464

def build_url(url = nil, extra_params = nil)
  uri = build_exclusive_url(url)

  query_values = params.dup.merge_query(uri.query, options.params_encoder)
  query_values.update(extra_params) if extra_params
  uri.query =
    if query_values.empty?
      nil
    else
      query_values.to_query(options.params_encoder)
    end

  uri
end

#dupFaraday::Connection

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a duplicate of this Faraday::Connection.

Returns:



552
553
554
555
556
557
558
559
# File 'lib/faraday/connection.rb', line 552

def dup
  self.class.new(build_exclusive_url,
                 headers: headers.dup,
                 params: params.dup,
                 builder: builder.dup,
                 ssl: ssl.dup,
                 request: options.dup)
end

#find_default_proxyObject



604
605
606
607
608
609
610
# File 'lib/faraday/connection.rb', line 604

def find_default_proxy
  uri = ENV['http_proxy']
  return unless uri && !uri.empty?

  uri = 'http://' + uri if uri !~ /^http/i
  uri
end

#in_parallel(manager = nil) { ... } ⇒ void

This method returns an undefined value.

Sets up the parallel manager to make a set of requests.

Parameters:

  • manager (Object) (defaults to: nil)

    The parallel manager that this Connection’s Adapter uses.

Yields:

  • a block to execute multiple requests.



381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/faraday/connection.rb', line 381

def in_parallel(manager = nil)
  @parallel_manager = manager || default_parallel_manager do
    warn 'Warning: `in_parallel` called but no parallel-capable adapter ' \
         'on Faraday stack'
    warn caller[2, 10].join("\n")
    nil
  end
  yield
  @parallel_manager&.run
ensure
  @parallel_manager = nil
end

#in_parallel?Boolean

Determine if this Faraday::Connection can make parallel requests.

Returns:

  • (Boolean)


370
371
372
# File 'lib/faraday/connection.rb', line 370

def in_parallel?
  !!@parallel_manager
end

#initialize_proxy(url, options) ⇒ Object



94
95
96
97
98
99
100
101
102
103
# File 'lib/faraday/connection.rb', line 94

def initialize_proxy(url, options)
  @manual_proxy = !!options.proxy
  @proxy =
    if options.proxy
      ProxyOptions.from(options.proxy)
    else
      proxy_from_env(url)
    end
  @temp_proxy = @proxy
end

#optionsFaraday::Response #options(url, params = nil, headers = nil) ⇒ Faraday::Response

Examples:

conn.options '/items/1'

Overloads:

  • #optionsFaraday::Response

    Returns current Connection options.

  • #options(url, params = nil, headers = nil) ⇒ Faraday::Response

    Makes an OPTIONS HTTP request to the given URL.

    Parameters:

    • url (String)

      String base URL to sue as a prefix for all requests.

    • params (Hash) (defaults to: nil)

      Hash of URI query unencoded key/value pairs.

    • headers (Hash) (defaults to: nil)

      unencoded HTTP header key/value pairs.

Yields:

Returns:



229
230
231
232
233
234
235
236
237
# File 'lib/faraday/connection.rb', line 229

def options(*args)
  return @options if args.size.zero?

  url, params, headers = *args
  run_request(:options, url, nil, headers) do |request|
    request.params.update(params) if params
    yield request if block_given?
  end
end

#path_prefix=(value) ⇒ String

Sets the path prefix and ensures that it always has a leading slash.

Parameters:

  • value (String)

Returns:

  • (String)

    the new path prefix



439
440
441
442
443
444
# File 'lib/faraday/connection.rb', line 439

def path_prefix=(value)
  url_prefix.path = if value
                      value = '/' + value unless value[0, 1] == '/'
                      value
                    end
end

#proxy_for_request(url) ⇒ Object



612
613
614
615
616
617
618
619
620
# File 'lib/faraday/connection.rb', line 612

def proxy_for_request(url)
  return proxy if @manual_proxy

  if url && Utils.URI(url).absolute?
    proxy_from_env(url)
  else
    proxy
  end
end

#proxy_from_env(url) ⇒ Object



583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/faraday/connection.rb', line 583

def proxy_from_env(url)
  return if Faraday.ignore_env_proxy

  uri = nil
  if URI.parse('').respond_to?(:find_proxy)
    case url
    when String
      uri = Utils.URI(url)
      uri = URI.parse("#{uri.scheme}://#{uri.hostname}").find_proxy
    when URI
      uri = url.find_proxy
    when nil
      uri = find_default_proxy
    end
  else
    warn 'no_proxy is unsupported' if ENV['no_proxy'] || ENV['NO_PROXY']
    uri = find_default_proxy
  end
  ProxyOptions.from(uri) if uri
end

#run_request(method, url, body, headers) ⇒ Faraday::Response

Builds and runs the Faraday::Request.

Parameters:

  • method (Symbol)

    HTTP method.

  • url (String, URI)

    String or URI to access.

  • body (Object)

    The request body that will eventually be converted to a string.

  • headers (Hash)

    unencoded HTTP header key/value pairs.

Returns:



488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
# File 'lib/faraday/connection.rb', line 488

def run_request(method, url, body, headers)
  unless METHODS.include?(method)
    raise ArgumentError, "unknown http method: #{method}"
  end

  # Resets temp_proxy
  @temp_proxy = proxy_for_request(url)

  request = build_request(method) do |req|
    req.options = req.options.merge(proxy: @temp_proxy)
    req.url(url)                if url
    req.headers.update(headers) if headers
    req.body = body             if body
    yield(req) if block_given?
  end

  builder.build_response(self, request)
end

#set_authorization_header(header_type, *args) ⇒ Object



575
576
577
578
579
580
581
# File 'lib/faraday/connection.rb', line 575

def set_authorization_header(header_type, *args)
  header = Faraday::Request
           .lookup_middleware(header_type)
           .header(*args)

  headers[Faraday::Request::Authorization::KEY] = header
end

#support_parallel?(adapter) ⇒ Boolean

Returns:

  • (Boolean)


622
623
624
# File 'lib/faraday/connection.rb', line 622

def support_parallel?(adapter)
  adapter&.respond_to?(:supports_parallel?) && adapter&.supports_parallel?
end

#token_auth(token, options = nil) ⇒ void

This method returns an undefined value.

Sets up the Authorization header with the given token.

Examples:


conn.token_auth 'abcdef', foo: 'bar'
conn.headers['Authorization']
# => "Token token=\"abcdef\",
            foo=\"bar\""

Parameters:

  • token (String)
  • options (Hash) (defaults to: nil)

    extra token options.



323
324
325
# File 'lib/faraday/connection.rb', line 323

def token_auth(token, options = nil)
  set_authorization_header(:token_auth, token, options)
end

#with_uri_credentials(uri) {|username, password| ... } ⇒ void

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

This method returns an undefined value.

Yields username and password extracted from a URI if they both exist.

Parameters:

  • uri (URI)

Yields:

  • (username, password)

    any username and password

Yield Parameters:

  • username (String)

    any username from URI

  • password (String)

    any password from URI



569
570
571
572
573
# File 'lib/faraday/connection.rb', line 569

def with_uri_credentials(uri)
  return unless uri.user && uri.password

  yield(Utils.unescape(uri.user), Utils.unescape(uri.password))
end