Module: RestClient

Defined in:
lib/restclient.rb,
lib/restclient/utils.rb,
lib/restclient/payload.rb,
lib/restclient/request.rb,
lib/restclient/version.rb,
lib/restclient/windows.rb,
lib/restclient/platform.rb,
lib/restclient/resource.rb,
lib/restclient/response.rb,
lib/restclient/exceptions.rb,
lib/restclient/params_array.rb,
lib/restclient/raw_response.rb,
lib/restclient/abstract_response.rb

Overview

This module’s static methods are the entry point for using the REST client.

# GET
xml = RestClient.get 'http://example.com/resource'
jpg = RestClient.get 'http://example.com/resource', :accept => 'image/jpg'

# authentication and SSL
RestClient.get 'https://user:[email protected]/private/resource'

# POST or PUT with a hash sends parameters as a urlencoded form body
RestClient.post 'http://example.com/resource', :param1 => 'one'

# nest hash parameters
RestClient.post 'http://example.com/resource', :nested => { :param1 => 'one' }

# POST and PUT with raw payloads
RestClient.post 'http://example.com/resource', 'the post body', :content_type => 'text/plain'
RestClient.post 'http://example.com/resource.xml', xml_doc
RestClient.put 'http://example.com/resource.pdf', File.read('my.pdf'), :content_type => 'application/pdf'

# DELETE
RestClient.delete 'http://example.com/resource'

# retrieve the response http code and headers
res = RestClient.get 'http://example.com/some.jpg'
res.code                    # => 200
res.headers[:content_type]  # => 'image/jpg'

# HEAD
RestClient.head('http://example.com').headers

To use with a proxy, just set RestClient.proxy to the proper http proxy:

RestClient.proxy = "http://proxy.example.com/"

Or inherit the proxy from the environment:

RestClient.proxy = ENV['http_proxy']

For live tests of RestClient, try using rest-test.heroku.com, which echoes back information about the rest call:

>> RestClient.put 'http://rest-test.heroku.com/resource', :foo => 'baz'
=> "PUT http://rest-test.heroku.com/resource with a 7 byte payload, content type application/x-www-form-urlencoded {\"foo\"=>\"baz\"}"

Defined Under Namespace

Modules: AbstractResponse, Exceptions, Payload, Platform, Utils, Windows Classes: Exception, ExceptionWithResponse, ParamsArray, RawResponse, Request, RequestFailed, Resource, Response, SSLCertificateNotVerified, ServerBrokeConnection

Constant Summary collapse

VERSION_INFO =
[2, 1, 0].freeze
VERSION =
VERSION_INFO.map(&:to_s).join('.').freeze
STATUSES =

Hash of HTTP status code => message.

1xx: Informational - Request received, continuing process 2xx: Success - The action was successfully received, understood, and

accepted

3xx: Redirection - Further action must be taken in order to complete the

request

4xx: Client Error - The request contains bad syntax or cannot be fulfilled 5xx: Server Error - The server failed to fulfill an apparently valid

request
{100 => 'Continue',
            101 => 'Switching Protocols',
            102 => 'Processing', #WebDAV

            200 => 'OK',
            201 => 'Created',
            202 => 'Accepted',
            203 => 'Non-Authoritative Information', # http/1.1
            204 => 'No Content',
            205 => 'Reset Content',
            206 => 'Partial Content',
            207 => 'Multi-Status', #WebDAV
            208 => 'Already Reported', # RFC5842
            226 => 'IM Used', # RFC3229

            300 => 'Multiple Choices',
            301 => 'Moved Permanently',
            302 => 'Found',
            303 => 'See Other', # http/1.1
            304 => 'Not Modified',
            305 => 'Use Proxy', # http/1.1
            306 => 'Switch Proxy', # no longer used
            307 => 'Temporary Redirect', # http/1.1
            308 => 'Permanent Redirect', # RFC7538

            400 => 'Bad Request',
            401 => 'Unauthorized',
            402 => 'Payment Required',
            403 => 'Forbidden',
            404 => 'Not Found',
            405 => 'Method Not Allowed',
            406 => 'Not Acceptable',
            407 => 'Proxy Authentication Required',
            408 => 'Request Timeout',
            409 => 'Conflict',
            410 => 'Gone',
            411 => 'Length Required',
            412 => 'Precondition Failed',
            413 => 'Payload Too Large', # RFC7231 (renamed, see below)
            414 => 'URI Too Long', # RFC7231 (renamed, see below)
            415 => 'Unsupported Media Type',
            416 => 'Range Not Satisfiable', # RFC7233 (renamed, see below)
            417 => 'Expectation Failed',
            418 => 'I\'m A Teapot', #RFC2324
            421 => 'Too Many Connections From This IP',
            422 => 'Unprocessable Entity', #WebDAV
            423 => 'Locked', #WebDAV
            424 => 'Failed Dependency', #WebDAV
            425 => 'Unordered Collection', #WebDAV
            426 => 'Upgrade Required',
            428 => 'Precondition Required', #RFC6585
            429 => 'Too Many Requests', #RFC6585
            431 => 'Request Header Fields Too Large', #RFC6585
            449 => 'Retry With', #Microsoft
            450 => 'Blocked By Windows Parental Controls', #Microsoft

            500 => 'Internal Server Error',
            501 => 'Not Implemented',
            502 => 'Bad Gateway',
            503 => 'Service Unavailable',
            504 => 'Gateway Timeout',
            505 => 'HTTP Version Not Supported',
            506 => 'Variant Also Negotiates',
            507 => 'Insufficient Storage', #WebDAV
            508 => 'Loop Detected', # RFC5842
            509 => 'Bandwidth Limit Exceeded', #Apache
            510 => 'Not Extended',
            511 => 'Network Authentication Required', # RFC6585
}
STATUSES_COMPATIBILITY =
{
  # The RFCs all specify "Not Found", but "Resource Not Found" was used in
  # earlier RestClient releases.
  404 => ['ResourceNotFound'],

  # HTTP 413 was renamed to "Payload Too Large" in RFC7231.
  413 => ['RequestEntityTooLarge'],

  # HTTP 414 was renamed to "URI Too Long" in RFC7231.
  414 => ['RequestURITooLong'],

  # HTTP 416 was renamed to "Range Not Satisfiable" in RFC7233.
  416 => ['RequestedRangeNotSatisfiable'],
}
@@env_log =
create_log ENV['RESTCLIENT_LOG']
@@log =
nil
@@before_execution_procs =
[]

Class Method Summary collapse

Class Method Details

.add_before_execution_proc(&proc) ⇒ Object

Add a Proc to be called before each request in executed. The proc parameters will be the http request and the request params.

Raises:

  • (ArgumentError)


169
170
171
172
# File 'lib/restclient.rb', line 169

def self.add_before_execution_proc &proc
  raise ArgumentError.new('block is required') unless proc
  @@before_execution_procs << proc
end

.before_execution_procsObject

:nodoc:



179
180
181
# File 'lib/restclient.rb', line 179

def self.before_execution_procs # :nodoc:
  @@before_execution_procs
end

.create_log(param) ⇒ Object

Create a log that respond to << like a logger param can be ‘stdout’, ‘stderr’, a string (then we will log to that file) or a logger (then we return it)



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/restclient.rb', line 122

def self.create_log param
  if param
    if param.is_a? String
      if param == 'stdout'
        stdout_logger = Class.new do
          def << obj
            STDOUT.puts obj
          end
        end
        stdout_logger.new
      elsif param == 'stderr'
        stderr_logger = Class.new do
          def << obj
            STDERR.puts obj
          end
        end
        stderr_logger.new
      else
        file_logger = Class.new do
          attr_writer :target_file

          def << obj
            File.open(@target_file, 'a') { |f| f.puts obj }
          end
        end
        logger = file_logger.new
        logger.target_file = param
        logger
      end
    else
      param
    end
  end
end

.delete(url, headers = {}, &block) ⇒ Object



81
82
83
# File 'lib/restclient.rb', line 81

def self.delete(url, headers={}, &block)
  Request.execute(:method => :delete, :url => url, :headers => headers, &block)
end

.get(url, headers = {}, &block) ⇒ Object



65
66
67
# File 'lib/restclient.rb', line 65

def self.get(url, headers={}, &block)
  Request.execute(:method => :get, :url => url, :headers => headers, &block)
end

.head(url, headers = {}, &block) ⇒ Object



85
86
87
# File 'lib/restclient.rb', line 85

def self.head(url, headers={}, &block)
  Request.execute(:method => :head, :url => url, :headers => headers, &block)
end

.logObject

:nodoc:



161
162
163
# File 'lib/restclient.rb', line 161

def self.log # :nodoc:
  @@env_log || @@log
end

.log=(log) ⇒ Object

Setup the log for RestClient calls. Value should be a logger but can can be stdout, stderr, or a filename. You can also configure logging by the environment variable RESTCLIENT_LOG.



116
117
118
# File 'lib/restclient.rb', line 116

def self.log= log
  @@log = create_log log
end

.options(url, headers = {}, &block) ⇒ Object



89
90
91
# File 'lib/restclient.rb', line 89

def self.options(url, headers={}, &block)
  Request.execute(:method => :options, :url => url, :headers => headers, &block)
end

.patch(url, payload, headers = {}, &block) ⇒ Object



73
74
75
# File 'lib/restclient.rb', line 73

def self.patch(url, payload, headers={}, &block)
  Request.execute(:method => :patch, :url => url, :payload => payload, :headers => headers, &block)
end

.post(url, payload, headers = {}, &block) ⇒ Object



69
70
71
# File 'lib/restclient.rb', line 69

def self.post(url, payload, headers={}, &block)
  Request.execute(:method => :post, :url => url, :payload => payload, :headers => headers, &block)
end

.proxyObject

A global proxy URL to use for all requests. This can be overridden on a per-request basis by passing ‘:proxy` to RestClient::Request.



95
96
97
# File 'lib/restclient.rb', line 95

def self.proxy
  @proxy ||= nil
end

.proxy=(value) ⇒ Object



99
100
101
102
# File 'lib/restclient.rb', line 99

def self.proxy=(value)
  @proxy = value
  @proxy_set = true
end

.proxy_set?Boolean

Return whether RestClient.proxy was set explicitly. We use this to differentiate between no value being set and a value explicitly set to nil.

Returns:

  • (Boolean)


109
110
111
# File 'lib/restclient.rb', line 109

def self.proxy_set?
  @proxy_set ||= false
end

.put(url, payload, headers = {}, &block) ⇒ Object



77
78
79
# File 'lib/restclient.rb', line 77

def self.put(url, payload, headers={}, &block)
  Request.execute(:method => :put, :url => url, :payload => payload, :headers => headers, &block)
end

.reset_before_execution_procsObject

Reset the procs to be called before each request is executed.



175
176
177
# File 'lib/restclient.rb', line 175

def self.reset_before_execution_procs
  @@before_execution_procs = []
end

.versionObject



5
6
7
# File 'lib/restclient/version.rb', line 5

def self.version
  VERSION
end