isteel-rest-client 0.9.3

Sign up to get free protection for your applications and to get access to all the features.
data/README.rdoc ADDED
@@ -0,0 +1,151 @@
1
+ = REST Client -- simple DSL for accessing REST resources
2
+
3
+ A simple REST client for Ruby, inspired by the Sinatra's microframework style
4
+ of specifying actions: get, put, post, delete.
5
+
6
+ == Usage: Raw URL
7
+
8
+ require 'rest_client'
9
+
10
+ RestClient.get 'http://example.com/resource'
11
+ RestClient.get 'https://user:password@example.com/private/resource'
12
+
13
+ RestClient.post 'http://example.com/resource', :param1 => 'one', :nested => { :param2 => 'two' }
14
+
15
+ RestClient.delete 'http://example.com/resource'
16
+
17
+ See RestClient module docs for details.
18
+
19
+ == Usage: ActiveResource-Style
20
+
21
+ resource = RestClient::Resource.new 'http://example.com/resource'
22
+ resource.get
23
+
24
+ private_resource = RestClient::Resource.new 'https://example.com/private/resource', :user => 'adam', :password => 'secret', :timeout => 20, :open_timeout => 5
25
+ private_resource.put File.read('pic.jpg'), :content_type => 'image/jpg'
26
+
27
+ See RestClient::Resource module docs for details.
28
+
29
+ == Usage: Resource Nesting
30
+
31
+ site = RestClient::Resource.new('http://example.com')
32
+ site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'
33
+
34
+ See RestClient::Resource docs for details.
35
+
36
+ == Shell
37
+
38
+ The restclient shell command gives an IRB session with RestClient already loaded:
39
+
40
+ $ restclient
41
+ >> RestClient.get 'http://example.com'
42
+
43
+ Specify a URL argument for get/post/put/delete on that resource:
44
+
45
+ $ restclient http://example.com
46
+ >> put '/resource', 'data'
47
+
48
+ Add a user and password for authenticated resources:
49
+
50
+ $ restclient https://example.com user pass
51
+ >> delete '/private/resource'
52
+
53
+ Create ~/.restclient for named sessions:
54
+
55
+ sinatra:
56
+ url: http://localhost:4567
57
+ rack:
58
+ url: http://localhost:9292
59
+ private_site:
60
+ url: http://example.com
61
+ username: user
62
+ password: pass
63
+
64
+ Then invoke:
65
+
66
+ $ restclient private_site
67
+
68
+ Use as a one-off, curl-style:
69
+
70
+ $ restclient get http://example.com/resource > output_body
71
+
72
+ $ restclient put http://example.com/resource < input_body
73
+
74
+ == Logging
75
+
76
+ Write calls to a log filename (can also be "stdout" or "stderr"):
77
+
78
+ RestClient.log = '/tmp/restclient.log'
79
+
80
+ Or set an environment variable to avoid modifying the code:
81
+
82
+ $ RESTCLIENT_LOG=stdout path/to/my/program
83
+
84
+ Either produces logs like this:
85
+
86
+ RestClient.get "http://some/resource"
87
+ # => 200 OK | text/html 250 bytes
88
+ RestClient.put "http://some/resource", "payload"
89
+ # => 401 Unauthorized | application/xml 340 bytes
90
+
91
+ Note that these logs are valid Ruby, so you can paste them into the restclient
92
+ shell or a script to replay your sequence of rest calls.
93
+
94
+ == Proxy
95
+
96
+ All calls to RestClient, including Resources, will use the proxy specified by
97
+ RestClient.proxy:
98
+
99
+ RestClient.proxy = "http://proxy.example.com/"
100
+ RestClient.get "http://some/resource"
101
+ # => response from some/resource as proxied through proxy.example.com
102
+
103
+ Often the proxy url is set in an environment variable, so you can do this to
104
+ use whatever proxy the system is configured to use:
105
+
106
+ RestClient.proxy = ENV['http_proxy']
107
+
108
+ == Cookies
109
+
110
+ Request and Response objects know about HTTP cookies, and will automatically
111
+ extract and set headers for them as needed:
112
+
113
+ response = RestClient.get 'http://example.com/action_which_sets_session_id'
114
+ response.cookies
115
+ # => {"_applicatioN_session_id" => "1234"}
116
+
117
+ response2 = RestClient.post(
118
+ 'http://localhost:3000/',
119
+ {:param1 => "foo"},
120
+ {:cookies => {:session_id => "1234"}}
121
+ )
122
+ # ...response body
123
+
124
+ == SSL Client Certificates
125
+
126
+ RestClient::Resource.new(
127
+ 'https://example.com',
128
+ :ssl_client_cert => OpenSSL::X509::Certificate.new(File.read("cert.pem")),
129
+ :ssl_client_key => OpenSSL::PKey::RSA.new(File.read("key.pem"), "passphrase, if any"),
130
+ :ssl_ca_file => "ca_certificate.pem",
131
+ :verify_ssl => OpenSSL::SSL::VERIFY_PEER
132
+ ).get
133
+
134
+ Self-signed certificates can be generated with the openssl command-line tool.
135
+
136
+ == Meta
137
+
138
+ Written by Adam Wiggins (adam at heroku dot com)
139
+
140
+ Patches contributed by: Chris Anderson, Greg Borenstein, Ardekantur, Pedro
141
+ Belo, Rafael Souza, Rick Olson, Aman Gupta, Blake Mizerany, Brian Donovan, Ivan
142
+ Makfinsky, Marc-André Cournoyer, Coda Hale, Tetsuo Watanabe, Dusty Doris,
143
+ Lennon Day-Reynolds, James Edward Gray II, Cyril Rohr, Juan Alvarez, and Adam
144
+ Jacob
145
+
146
+ Released under the MIT License: http://www.opensource.org/licenses/mit-license.php
147
+
148
+ http://rest-client.heroku.com
149
+
150
+ http://github.com/adamwiggins/rest-client
151
+
data/Rakefile ADDED
@@ -0,0 +1,85 @@
1
+ require 'rake'
2
+ require 'spec/rake/spectask'
3
+
4
+ desc "Run all specs"
5
+ Spec::Rake::SpecTask.new('spec') do |t|
6
+ t.spec_opts = ['--colour --format progress --loadby mtime --reverse']
7
+ t.spec_files = FileList['spec/*_spec.rb']
8
+ end
9
+
10
+ desc "Print specdocs"
11
+ Spec::Rake::SpecTask.new(:doc) do |t|
12
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
13
+ t.spec_files = FileList['spec/*_spec.rb']
14
+ end
15
+
16
+ desc "Run all examples with RCov"
17
+ Spec::Rake::SpecTask.new('rcov') do |t|
18
+ t.spec_files = FileList['spec/*_spec.rb']
19
+ t.rcov = true
20
+ t.rcov_opts = ['--exclude', 'examples']
21
+ end
22
+
23
+ task :default => :spec
24
+
25
+ ######################################################
26
+
27
+ require 'rake'
28
+ require 'rake/testtask'
29
+ require 'rake/clean'
30
+ require 'rake/gempackagetask'
31
+ require 'rake/rdoctask'
32
+ require 'fileutils'
33
+
34
+ version = "0.9.2"
35
+ name = "rest-client"
36
+
37
+ spec = Gem::Specification.new do |s|
38
+ s.name = name
39
+ s.version = version
40
+ s.summary = "Simple REST client for Ruby, inspired by microframework syntax for specifying actions."
41
+ s.description = "A simple REST client for Ruby, inspired by the Sinatra microframework style of specifying actions: get, put, post, delete."
42
+ s.author = "Adam Wiggins"
43
+ s.email = "adam@heroku.com"
44
+ s.homepage = "http://rest-client.heroku.com/"
45
+ s.rubyforge_project = "rest-client"
46
+
47
+ s.platform = Gem::Platform::RUBY
48
+ s.has_rdoc = true
49
+
50
+ s.files = %w(Rakefile README.rdoc) + Dir.glob("{lib,spec}/**/*")
51
+ s.executables = ['restclient']
52
+
53
+ s.require_path = "lib"
54
+ end
55
+
56
+ Rake::GemPackageTask.new(spec) do |p|
57
+ p.need_tar = true if RUBY_PLATFORM !~ /mswin/
58
+ end
59
+
60
+ task :install => [ :package ] do
61
+ sh %{sudo gem install pkg/#{name}-#{version}.gem}
62
+ end
63
+
64
+ task :uninstall => [ :clean ] do
65
+ sh %{sudo gem uninstall #{name}}
66
+ end
67
+
68
+ Rake::TestTask.new do |t|
69
+ t.libs << "spec"
70
+ t.test_files = FileList['spec/*_spec.rb']
71
+ t.verbose = true
72
+ end
73
+
74
+ Rake::RDocTask.new do |t|
75
+ t.rdoc_dir = 'rdoc'
76
+ t.title = "rest-client, fetch RESTful resources effortlessly"
77
+ t.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
78
+ t.options << '--charset' << 'utf-8'
79
+ t.rdoc_files.include('README.rdoc')
80
+ t.rdoc_files.include('lib/restclient.rb')
81
+ t.rdoc_files.include('lib/restclient/*.rb')
82
+ end
83
+
84
+ CLEAN.include [ 'pkg', '*.gem', '.config' ]
85
+
data/bin/restclient ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ $:.unshift File.dirname(__FILE__) + "/../lib"
4
+ require 'restclient'
5
+
6
+ require "yaml"
7
+
8
+ def usage(why = nil)
9
+ puts "failed for reason: #{why}" if why
10
+ puts "usage: restclient [get|put|post|delete] url|name [username] [password]"
11
+ puts " The verb is optional, if you leave it off you'll get an interactive shell."
12
+ puts " put and post both take the input body on stdin."
13
+ exit(1)
14
+ end
15
+
16
+ if %w(get put post delete).include? ARGV.first
17
+ @verb = ARGV.shift
18
+ else
19
+ @verb = nil
20
+ end
21
+
22
+ @url = ARGV.shift || 'http://localhost:4567'
23
+
24
+ config = YAML.load(File.read(ENV['HOME'] + "/.restclient")) rescue {}
25
+
26
+ @url, @username, @password = if c = config[@url]
27
+ [c['url'], c['username'], c['password']]
28
+ else
29
+ [@url, *ARGV]
30
+ end
31
+
32
+ usage("invalid url '#{@url}") unless @url =~ /^https?/
33
+ usage("too few args") unless ARGV.size < 3
34
+
35
+ def r
36
+ @r ||= RestClient::Resource.new(@url, @username, @password)
37
+ end
38
+
39
+ r # force rc to load
40
+
41
+ if @verb
42
+ begin
43
+ if %w(put post).include? @verb
44
+ puts r.send(@verb, STDIN.read)
45
+ else
46
+ puts r.send(@verb)
47
+ end
48
+ exit 0
49
+ rescue RestClient::Exception => e
50
+ puts e.response.body if e.respond_to? :response
51
+ raise
52
+ end
53
+ end
54
+
55
+ %w(get post put delete).each do |m|
56
+ eval <<-end_eval
57
+ def #{m}(path, *args, &b)
58
+ r[path].#{m}(*args, &b)
59
+ end
60
+ end_eval
61
+ end
62
+
63
+ def method_missing(s, *args, &b)
64
+ super unless r.respond_to?(s)
65
+ begin
66
+ r.send(s, *args, &b)
67
+ rescue RestClient::RequestFailed => e
68
+ print STDERR, e.response.body
69
+ raise e
70
+ end
71
+ end
72
+
73
+ require 'irb'
74
+ require 'irb/completion'
75
+
76
+ if File.exists? ".irbrc"
77
+ ENV['IRBRC'] = ".irbrc"
78
+ end
79
+
80
+ if File.exists?(rcfile = "~/.restclientrc")
81
+ load(rcfile)
82
+ end
83
+
84
+ ARGV.clear
85
+
86
+ IRB.start
87
+ exit!
@@ -0,0 +1,2 @@
1
+ # This file exists for backward compatbility with require 'rest_client'
2
+ require File.dirname(__FILE__) + '/restclient'
@@ -0,0 +1,84 @@
1
+ module RestClient
2
+ # This is the base RestClient exception class. Rescue it if you want to
3
+ # catch any exception that your request might raise
4
+ class Exception < RuntimeError
5
+ def message(default=nil)
6
+ self.class::ErrorMessage
7
+ end
8
+ end
9
+
10
+ # Base RestClient exception when there's a response available
11
+ class ExceptionWithResponse < Exception
12
+ attr_accessor :response
13
+
14
+ def initialize(response=nil)
15
+ @response = response
16
+ end
17
+
18
+ def http_code
19
+ @response.code.to_i if @response
20
+ end
21
+ end
22
+
23
+ # A redirect was encountered; caught by execute to retry with the new url.
24
+ class Redirect < Exception
25
+ ErrorMessage = "Redirect"
26
+
27
+ attr_accessor :url
28
+ def initialize(url)
29
+ @url = url
30
+ end
31
+ end
32
+
33
+ class NotModified < ExceptionWithResponse
34
+ ErrorMessage = 'NotModified'
35
+ end
36
+
37
+ # Authorization is required to access the resource specified.
38
+ class Unauthorized < ExceptionWithResponse
39
+ ErrorMessage = 'Unauthorized'
40
+ end
41
+
42
+ # No resource was found at the given URL.
43
+ class ResourceNotFound < ExceptionWithResponse
44
+ ErrorMessage = 'Resource not found'
45
+ end
46
+
47
+ # The server broke the connection prior to the request completing. Usually
48
+ # this means it crashed, or sometimes that your network connection was
49
+ # severed before it could complete.
50
+ class ServerBrokeConnection < Exception
51
+ ErrorMessage = 'Server broke connection'
52
+ end
53
+
54
+ # The server took too long to respond.
55
+ class RequestTimeout < Exception
56
+ ErrorMessage = 'Request timed out'
57
+ end
58
+
59
+ # The request failed, meaning the remote HTTP server returned a code other
60
+ # than success, unauthorized, or redirect.
61
+ #
62
+ # The exception message attempts to extract the error from the XML, using
63
+ # format returned by Rails: <errors><error>some message</error></errors>
64
+ #
65
+ # You can get the status code by e.http_code, or see anything about the
66
+ # response via e.response. For example, the entire result body (which is
67
+ # probably an HTML error page) is e.response.body.
68
+ class RequestFailed < ExceptionWithResponse
69
+ def message
70
+ "HTTP status code #{http_code}"
71
+ end
72
+
73
+ def to_s
74
+ message
75
+ end
76
+ end
77
+ end
78
+
79
+ # backwards compatibility
80
+ class RestClient::Request
81
+ Redirect = RestClient::Redirect
82
+ Unauthorized = RestClient::Unauthorized
83
+ RequestFailed = RestClient::RequestFailed
84
+ end
@@ -0,0 +1,239 @@
1
+ require 'tempfile'
2
+
3
+ module RestClient
4
+ # This class is used internally by RestClient to send the request, but you can also
5
+ # access it internally if you'd like to use a method not directly supported by the
6
+ # main API. For example:
7
+ #
8
+ # RestClient::Request.execute(:method => :head, :url => 'http://example.com')
9
+ #
10
+ class Request
11
+ attr_reader :method, :url, :payload, :headers,
12
+ :cookies, :user, :password, :timeout, :open_timeout,
13
+ :verify_ssl, :ssl_client_cert, :ssl_client_key, :ssl_ca_file,
14
+ :raw_response
15
+
16
+ def self.execute(args)
17
+ new(args).execute
18
+ end
19
+
20
+ def initialize(args)
21
+ @method = args[:method] or raise ArgumentError, "must pass :method"
22
+ @url = args[:url] or raise ArgumentError, "must pass :url"
23
+ @headers = args[:headers] || {}
24
+ @cookies = @headers.delete(:cookies) || args[:cookies] || {}
25
+ @payload = process_payload(args[:payload])
26
+ @user = args[:user]
27
+ @password = args[:password]
28
+ @timeout = args[:timeout]
29
+ @open_timeout = args[:open_timeout]
30
+ @raw_response = args[:raw_response] || false
31
+ @verify_ssl = args[:verify_ssl] || false
32
+ @ssl_client_cert = args[:ssl_client_cert] || nil
33
+ @ssl_client_key = args[:ssl_client_key] || nil
34
+ @ssl_ca_file = args[:ssl_ca_file] || nil
35
+ @tf = nil # If you are a raw request, this is your tempfile
36
+ end
37
+
38
+ def execute
39
+ execute_inner
40
+ rescue Redirect => e
41
+ @url = e.url
42
+ execute
43
+ end
44
+
45
+ def execute_inner
46
+ uri = parse_url_with_auth(url)
47
+ transmit uri, net_http_request_class(method).new(uri.request_uri, make_headers(headers)), payload
48
+ end
49
+
50
+ def make_headers(user_headers)
51
+ unless @cookies.empty?
52
+ user_headers[:cookie] = @cookies.map {|key, val| "#{key.to_s}=#{val}" }.join('; ')
53
+ end
54
+
55
+ default_headers.merge(user_headers).inject({}) do |final, (key, value)|
56
+ final[key.to_s.gsub(/_/, '-').capitalize] = value.to_s
57
+ final
58
+ end
59
+ end
60
+
61
+ def net_http_class
62
+ if RestClient.proxy
63
+ proxy_uri = URI.parse(RestClient.proxy)
64
+ Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)
65
+ else
66
+ Net::HTTP
67
+ end
68
+ end
69
+
70
+ def net_http_request_class(method)
71
+ Net::HTTP.const_get(method.to_s.capitalize)
72
+ end
73
+
74
+ def parse_url(url)
75
+ url = "http://#{url}" unless url.match(/^http/)
76
+ URI.parse(url)
77
+ end
78
+
79
+ def parse_url_with_auth(url)
80
+ uri = parse_url(url)
81
+ @user = uri.user if uri.user
82
+ @password = uri.password if uri.password
83
+ uri
84
+ end
85
+
86
+ def process_payload(p=nil, parent_key=nil)
87
+ unless p.is_a?(Hash)
88
+ p
89
+ else
90
+ @headers[:content_type] ||= 'application/x-www-form-urlencoded'
91
+ p.keys.map do |k|
92
+ key = parent_key ? "#{parent_key}[#{k}]" : k
93
+ if p[k].is_a? Hash
94
+ process_payload(p[k], key)
95
+ elsif p[k].is_a? Array
96
+ ret=[]
97
+ p[k].each do |e|
98
+ value = URI.escape(e.to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
99
+ ret << "#{key}[]=#{value}"
100
+ end
101
+ ret.join("&")
102
+ else
103
+ value = URI.escape(p[k].to_s, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))
104
+ "#{key}=#{value}"
105
+ end
106
+ end.join("&")
107
+ end
108
+ end
109
+
110
+ def transmit(uri, req, payload)
111
+ setup_credentials(req)
112
+
113
+ net = net_http_class.new(uri.host, uri.port)
114
+ net.use_ssl = uri.is_a?(URI::HTTPS)
115
+ net.verify_mode = OpenSSL::SSL::VERIFY_NONE if @verify_ssl == false
116
+ net.cert = @ssl_client_cert if @ssl_client_cert
117
+ net.key = @ssl_client_key if @ssl_client_key
118
+ net.ca_file = @ssl_ca_file if @ssl_ca_file
119
+ net.read_timeout = @timeout if @timeout
120
+ net.open_timeout = @open_timeout if @open_timeout
121
+
122
+ display_log request_log
123
+
124
+ net.start do |http|
125
+ res = http.request(req, payload) { |http_response| fetch_body(http_response) }
126
+ result = process_result(res)
127
+ display_log response_log(res)
128
+
129
+ if result.kind_of?(String) or @method == :head
130
+ Response.new(result, res)
131
+ elsif @raw_response
132
+ RawResponse.new(@tf, res)
133
+ else
134
+ nil
135
+ end
136
+ end
137
+ rescue EOFError
138
+ raise RestClient::ServerBrokeConnection
139
+ rescue Timeout::Error
140
+ raise RestClient::RequestTimeout
141
+ end
142
+
143
+ def setup_credentials(req)
144
+ req.basic_auth(user, password) if user
145
+ end
146
+
147
+ def fetch_body(http_response)
148
+ if @raw_response
149
+ # Taken from Chef, which as in turn...
150
+ # Stolen from http://www.ruby-forum.com/topic/166423
151
+ # Kudos to _why!
152
+ @tf = Tempfile.new("rest-client")
153
+ size, total = 0, http_response.header['Content-Length'].to_i
154
+ http_response.read_body do |chunk|
155
+ @tf.write(chunk)
156
+ size += chunk.size
157
+ if size == 0
158
+ display_log("#{@method} #{@url} done (0 length file)")
159
+ elsif total == 0
160
+ display_log("#{@method} #{@url} (zero content length)")
161
+ else
162
+ display_log("#{@method} #{@url} %d%% done (%d of %d)" % [(size * 100) / total, size, total])
163
+ end
164
+ end
165
+ @tf.close
166
+ @tf
167
+ else
168
+ http_response.read_body
169
+ end
170
+ http_response
171
+ end
172
+
173
+ def process_result(res)
174
+ if res.code =~ /\A2\d{2}\z/
175
+ # We don't decode raw requests
176
+ unless @raw_response
177
+ decode res['content-encoding'], res.body if res.body
178
+ end
179
+ elsif %w(301 302 303).include? res.code
180
+ url = res.header['Location']
181
+
182
+ if url !~ /^http/
183
+ uri = URI.parse(@url)
184
+ uri.path = "/#{url}".squeeze('/')
185
+ url = uri.to_s
186
+ end
187
+
188
+ raise Redirect, url
189
+ elsif res.code == "304"
190
+ raise NotModified, res
191
+ elsif res.code == "401"
192
+ raise Unauthorized, res
193
+ elsif res.code == "404"
194
+ raise ResourceNotFound, res
195
+ else
196
+ raise RequestFailed, res
197
+ end
198
+ end
199
+
200
+ def decode(content_encoding, body)
201
+ if content_encoding == 'gzip' and not body.empty?
202
+ Zlib::GzipReader.new(StringIO.new(body)).read
203
+ elsif content_encoding == 'deflate'
204
+ Zlib::Inflate.new.inflate(body)
205
+ else
206
+ body
207
+ end
208
+ end
209
+
210
+ def request_log
211
+ out = []
212
+ out << "RestClient.#{method} #{url.inspect}"
213
+ out << (payload.size > 100 ? "(#{payload.size} byte payload)".inspect : payload.inspect) if payload
214
+ out << headers.inspect.gsub(/^\{/, '').gsub(/\}$/, '') unless headers.empty?
215
+ out.join(', ')
216
+ end
217
+
218
+ def response_log(res)
219
+ size = @raw_response ? File.size(@tf.path) : res.body.size
220
+ "# => #{res.code} #{res.class.to_s.gsub(/^Net::HTTP/, '')} | #{(res['Content-type'] || '').gsub(/;.*$/, '')} #{size} bytes"
221
+ end
222
+
223
+ def display_log(msg)
224
+ return unless log_to = RestClient.log
225
+
226
+ if log_to == 'stdout'
227
+ STDOUT.puts msg
228
+ elsif log_to == 'stderr'
229
+ STDERR.puts msg
230
+ else
231
+ File.open(log_to, 'a') { |f| f.puts msg }
232
+ end
233
+ end
234
+
235
+ def default_headers
236
+ { :accept => 'application/xml', :accept_encoding => 'gzip, deflate' }
237
+ end
238
+ end
239
+ end