esank-rest-client 1.6.7

Sign up to get free protection for your applications and to get access to all the features.
data/README.rdoc ADDED
@@ -0,0 +1,285 @@
1
+ = REST Client -- simple DSL for accessing HTTP and REST resources
2
+
3
+ A simple HTTP and REST client for Ruby, inspired by the Sinatra's microframework style
4
+ of specifying actions: get, put, post, delete.
5
+
6
+ * Main page: http://github.com/archiloque/rest-client
7
+ * Mailing list: rest.client@librelist.com (send a mail to subscribe).
8
+
9
+ == Usage: Raw URL
10
+
11
+ require 'rest_client'
12
+
13
+ RestClient.get 'http://example.com/resource'
14
+
15
+ RestClient.get 'http://example.com/resource', {:params => {:id => 50, 'foo' => 'bar'}}
16
+
17
+ RestClient.get 'https://user:password@example.com/private/resource', {:accept => :json}
18
+
19
+ RestClient.post 'http://example.com/resource', :param1 => 'one', :nested => { :param2 => 'two' }
20
+
21
+ RestClient.post "http://example.com/resource", { 'x' => 1 }.to_json, :content_type => :json, :accept => :json
22
+
23
+ RestClient.delete 'http://example.com/resource'
24
+
25
+ response = RestClient.get 'http://example.com/resource'
26
+ response.code
27
+ ➔ 200
28
+ response.cookies
29
+ ➔ {"Foo"=>"BAR", "QUUX"=>"QUUUUX"}
30
+ response.headers
31
+ ➔ {:content_type=>"text/html; charset=utf-8", :cache_control=>"private" ...
32
+ response.to_str
33
+ ➔ \n<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n\n<html ....
34
+
35
+ RestClient.post( url,
36
+ {
37
+ :transfer => {
38
+ :path => '/foo/bar',
39
+ :owner => 'that_guy',
40
+ :group => 'those_guys'
41
+ },
42
+ :upload => {
43
+ :file => File.new(path, 'rb')
44
+ }
45
+ })
46
+
47
+ == Multipart
48
+
49
+ Yeah, that's right! This does multipart sends for you!
50
+
51
+ RestClient.post '/data', :myfile => File.new("/path/to/image.jpg", 'rb')
52
+
53
+ This does two things for you:
54
+
55
+ * Auto-detects that you have a File value sends it as multipart
56
+ * Auto-detects the mime of the file and sets it in the HEAD of the payload for each entry
57
+
58
+ If you are sending params that do not contain a File object but the payload needs to be multipart then:
59
+
60
+ RestClient.post '/data', {:foo => 'bar', :multipart => true}
61
+
62
+ == Usage: ActiveResource-Style
63
+
64
+ resource = RestClient::Resource.new 'http://example.com/resource'
65
+ resource.get
66
+
67
+ private_resource = RestClient::Resource.new 'https://example.com/private/resource', 'user', 'pass'
68
+ private_resource.put File.read('pic.jpg'), :content_type => 'image/jpg'
69
+
70
+ See RestClient::Resource module docs for details.
71
+
72
+ == Usage: Resource Nesting
73
+
74
+ site = RestClient::Resource.new('http://example.com')
75
+ site['posts/1/comments'].post 'Good article.', :content_type => 'text/plain'
76
+
77
+ See RestClient::Resource docs for details.
78
+
79
+ == Exceptions (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)
80
+
81
+ * for results code between 200 and 207 a RestClient::Response will be returned
82
+ * for results code 301, 302 or 307 the redirection will be followed if the request is a get or a head
83
+ * for result code 303 the redirection will be followed and the request transformed into a get
84
+ * for other cases a RestClient::Exception holding the Response will be raised, a specific exception class will be thrown for know error codes
85
+
86
+ RestClient.get 'http://example.com/resource'
87
+ ➔ RestClient::ResourceNotFound: RestClient::ResourceNotFound
88
+
89
+ begin
90
+ RestClient.get 'http://example.com/resource'
91
+ rescue => e
92
+ e.response
93
+ end
94
+ ➔ 404 Resource Not Found | text/html 282 bytes
95
+
96
+ == Result handling
97
+
98
+ A block can be passed to the RestClient method, this block will then be called with the Response.
99
+ Response.return! can be called to invoke the default response's behavior.
100
+
101
+ # Don't raise exceptions but return the response
102
+ RestClient.get('http://example.com/resource'){|response, request, result| response }
103
+ ➔ 404 Resource Not Found | text/html 282 bytes
104
+
105
+ # Manage a specific error code
106
+ RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block|
107
+ case response.code
108
+ when 200
109
+ p "It worked !"
110
+ response
111
+ when 423
112
+ raise SomeCustomExceptionIfYouWant
113
+ else
114
+ response.return!(request, result, &block)
115
+ end
116
+ }
117
+
118
+ # Follow redirections for all request types and not only for get and head
119
+ # RFC : "If the 301, 302 or 307 status code is received in response to a request other than GET or HEAD,
120
+ # the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user,
121
+ # since this might change the conditions under which the request was issued."
122
+ RestClient.get('http://my-rest-service.com/resource'){ |response, request, result, &block|
123
+ if [301, 302, 307].include? response.code
124
+ response.follow_redirection(request, result, &block)
125
+ else
126
+ response.return!(request, result, &block)
127
+ end
128
+ }
129
+
130
+ == Non-normalized URIs.
131
+
132
+ If you want to use non-normalized URIs, you can normalize them with the addressable gem (http://addressable.rubyforge.org/api/).
133
+
134
+ require 'addressable/uri'
135
+ RestClient.get(Addressable::URI.parse("http://www.詹姆斯.com/").normalize.to_str)
136
+
137
+ == Lower-level access
138
+
139
+ For cases not covered by the general API, you can use the RestClient::Request class which provide a lower-level API.
140
+
141
+ You can:
142
+
143
+ * specify ssl parameters
144
+ * override cookies
145
+ * manually handle the response (so you can operate on the response stream than reading it fully in memory)
146
+
147
+ see the class' rdoc for more information.
148
+
149
+ == Shell
150
+
151
+ The restclient shell command gives an IRB session with RestClient already loaded:
152
+
153
+ $ restclient
154
+ >> RestClient.get 'http://example.com'
155
+
156
+ Specify a URL argument for get/post/put/delete on that resource:
157
+
158
+ $ restclient http://example.com
159
+ >> put '/resource', 'data'
160
+
161
+ Add a user and password for authenticated resources:
162
+
163
+ $ restclient https://example.com user pass
164
+ >> delete '/private/resource'
165
+
166
+ Create ~/.restclient for named sessions:
167
+
168
+ sinatra:
169
+ url: http://localhost:4567
170
+ rack:
171
+ url: http://localhost:9292
172
+ private_site:
173
+ url: http://example.com
174
+ username: user
175
+ password: pass
176
+
177
+ Then invoke:
178
+
179
+ $ restclient private_site
180
+
181
+ Use as a one-off, curl-style:
182
+
183
+ $ restclient get http://example.com/resource > output_body
184
+
185
+ $ restclient put http://example.com/resource < input_body
186
+
187
+ == Logging
188
+
189
+ To enable logging you can
190
+
191
+ * set RestClient.log with a ruby Logger
192
+ * or set an environment variable to avoid modifying the code (in this case you can use a file name, "stdout" or "stderr"):
193
+
194
+ $ RESTCLIENT_LOG=stdout path/to/my/program
195
+
196
+ Either produces logs like this:
197
+
198
+ RestClient.get "http://some/resource"
199
+ # => 200 OK | text/html 250 bytes
200
+ RestClient.put "http://some/resource", "payload"
201
+ # => 401 Unauthorized | application/xml 340 bytes
202
+
203
+ Note that these logs are valid Ruby, so you can paste them into the restclient
204
+ shell or a script to replay your sequence of rest calls.
205
+
206
+ == Proxy
207
+
208
+ All calls to RestClient, including Resources, will use the proxy specified by
209
+ RestClient.proxy:
210
+
211
+ RestClient.proxy = "http://proxy.example.com/"
212
+ RestClient.get "http://some/resource"
213
+ # => response from some/resource as proxied through proxy.example.com
214
+
215
+ Often the proxy url is set in an environment variable, so you can do this to
216
+ use whatever proxy the system is configured to use:
217
+
218
+ RestClient.proxy = ENV['http_proxy']
219
+
220
+ == Query parameters
221
+
222
+ Request objects know about query parameters and will automatically add them to
223
+ the url for GET, HEAD and DELETE requests and escape the keys and values as
224
+ needed:
225
+
226
+ RestClient.get 'http://example.com/resource', :params => {:foo => 'bar', :baz => 'qux'}
227
+ # will GET http://example.com/resource?foo=bar&baz=qux
228
+
229
+ == Cookies
230
+
231
+ Request and Response objects know about HTTP cookies, and will automatically
232
+ extract and set headers for them as needed:
233
+
234
+ response = RestClient.get 'http://example.com/action_which_sets_session_id'
235
+ response.cookies
236
+ # => {"_applicatioN_session_id" => "1234"}
237
+
238
+ response2 = RestClient.post(
239
+ 'http://localhost:3000/',
240
+ {:param1 => "foo"},
241
+ {:cookies => {:session_id => "1234"}}
242
+ )
243
+ # ...response body
244
+
245
+ == SSL Client Certificates
246
+
247
+ RestClient::Resource.new(
248
+ 'https://example.com',
249
+ :ssl_client_cert => OpenSSL::X509::Certificate.new(File.read("cert.pem")),
250
+ :ssl_client_key => OpenSSL::PKey::RSA.new(File.read("key.pem"), "passphrase, if any"),
251
+ :ssl_ca_file => "ca_certificate.pem",
252
+ :verify_ssl => OpenSSL::SSL::VERIFY_PEER
253
+ ).get
254
+
255
+ Self-signed certificates can be generated with the openssl command-line tool.
256
+
257
+ == Hook
258
+
259
+ RestClient.add_before_execution_proc add a Proc to be called before each execution, it's handy if you need a direct access to the http request.
260
+
261
+ Example:
262
+
263
+ # Add oath support using the oauth gem
264
+ require 'oauth'
265
+ access_token = ...
266
+
267
+ RestClient.add_before_execution_proc do |req, params|
268
+ access_token.sign! req
269
+ end
270
+
271
+ RestClient.get 'http://example.com'
272
+
273
+ == More
274
+
275
+ Need caching, more advanced logging or any ability provided by a rack middleware ?
276
+
277
+ Have a look at rest-client-components http://github.com/crohr/rest-client-components
278
+
279
+ == Meta
280
+
281
+ Written by Adam Wiggins, major modifications by Blake Mizerany, maintained by Julien Kirch
282
+
283
+ Patches contributed by many, including Chris Anderson, Greg Borenstein, Ardekantur, Pedro Belo, Rafael Souza, Rick Olson, Aman Gupta, François Beausoleil and Nick Plante.
284
+
285
+ Released under the MIT License: http://www.opensource.org/licenses/mit-license.php
data/Rakefile ADDED
@@ -0,0 +1,66 @@
1
+ require 'rake'
2
+
3
+ require 'jeweler'
4
+
5
+ Jeweler::Tasks.new do |s|
6
+ s.name = "rest-client"
7
+ s.description = "A simple HTTP and REST client for Ruby, inspired by the Sinatra microframework style of specifying actions: get, put, post, delete."
8
+ s.summary = "Simple HTTP and REST client for Ruby, inspired by microframework syntax for specifying actions."
9
+ s.authors = ["Adam Wiggins", "Julien Kirch"]
10
+ s.email = "rest.client@librelist.com"
11
+ s.homepage = "http://github.com/archiloque/rest-client"
12
+ s.files = FileList["[A-Z]*", "{bin,lib,spec}/**/*"]
13
+ s.test_files = FileList["{spec}/**/*"]
14
+ s.add_runtime_dependency("mime-types", ">= 1.16")
15
+ s.add_development_dependency("webmock", ">= 0.9.1")
16
+ s.add_development_dependency("rspec")
17
+ s.extra_rdoc_files = [ 'README.rdoc', 'history.md']
18
+ end
19
+
20
+ ############################
21
+
22
+ require 'spec/rake/spectask'
23
+
24
+ desc "Run all specs"
25
+ task :spec => ["spec:unit", "spec:integration"]
26
+
27
+ desc "Run unit specs"
28
+ Spec::Rake::SpecTask.new('spec:unit') do |t|
29
+ t.spec_opts = ['--colour --format progress --loadby mtime --reverse']
30
+ t.spec_files = FileList['spec/*_spec.rb']
31
+ end
32
+
33
+ desc "Run integration specs"
34
+ Spec::Rake::SpecTask.new('spec:integration') do |t|
35
+ t.spec_opts = ['--colour --format progress --loadby mtime --reverse']
36
+ t.spec_files = FileList['spec/integration/*_spec.rb']
37
+ end
38
+
39
+ desc "Print specdocs"
40
+ Spec::Rake::SpecTask.new(:doc) do |t|
41
+ t.spec_opts = ["--format", "specdoc", "--dry-run"]
42
+ t.spec_files = FileList['spec/*_spec.rb']
43
+ end
44
+
45
+ desc "Run all examples with RCov"
46
+ Spec::Rake::SpecTask.new('rcov') do |t|
47
+ t.spec_files = FileList['spec/*_spec.rb']
48
+ t.rcov = true
49
+ t.rcov_opts = ['--exclude', 'examples']
50
+ end
51
+
52
+ task :default => :spec
53
+
54
+ ############################
55
+
56
+ require 'rake/rdoctask'
57
+
58
+ Rake::RDocTask.new do |t|
59
+ t.rdoc_dir = 'rdoc'
60
+ t.title = "rest-client, fetch RESTful resources effortlessly"
61
+ t.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
62
+ t.options << '--charset' << 'utf-8'
63
+ t.rdoc_files.include('README.rdoc')
64
+ t.rdoc_files.include('lib/*.rb')
65
+ end
66
+
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.6.7
data/bin/restclient ADDED
@@ -0,0 +1,93 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ $:.unshift File.dirname(__FILE__) + "/../lib"
4
+
5
+ require 'rubygems'
6
+ require 'restclient'
7
+ require 'yaml'
8
+
9
+ def usage(why = nil)
10
+ puts "failed for reason: #{why}" if why
11
+ puts "usage: restclient [get|put|post|delete] url|name [username] [password]"
12
+ puts " The verb is optional, if you leave it off you'll get an interactive shell."
13
+ puts " put and post both take the input body on stdin."
14
+ exit(1)
15
+ end
16
+
17
+ POSSIBLE_VERBS = ['get', 'put', 'post', 'delete']
18
+
19
+ if POSSIBLE_VERBS.include? ARGV.first
20
+ @verb = ARGV.shift
21
+ else
22
+ @verb = nil
23
+ end
24
+
25
+ @url = ARGV.shift || 'http://localhost:4567'
26
+
27
+ config = YAML.load(File.read(ENV['HOME'] + "/.restclient")) rescue {}
28
+
29
+ @url, @username, @password = if c = config[@url]
30
+ [c['url'], c['username'], c['password']]
31
+ else
32
+ [@url, * ARGV]
33
+ end
34
+
35
+ usage("invalid url '#{@url}") unless @url =~ /^https?/
36
+ usage("too few args") unless ARGV.size < 3
37
+
38
+ def r
39
+ @r ||= RestClient::Resource.new(@url, @username, @password)
40
+ end
41
+
42
+ r # force rc to load
43
+
44
+ if @verb
45
+ begin
46
+ if %w( put post ).include? @verb
47
+ puts r.send(@verb, STDIN.read)
48
+ else
49
+ puts r.send(@verb)
50
+ end
51
+ exit 0
52
+ rescue RestClient::Exception => e
53
+ puts e.response.body if e.respond_to? :response
54
+ raise
55
+ end
56
+ end
57
+
58
+ POSSIBLE_VERBS.each do |m|
59
+ eval <<-end_eval
60
+ def #{m}(path, *args, &b)
61
+ r[path].#{m}(*args, &b)
62
+ end
63
+ end_eval
64
+ end
65
+
66
+ def method_missing(s, * args, & b)
67
+ if POSSIBLE_VERBS.include? s
68
+ begin
69
+ r.send(s, *args, & b)
70
+ rescue RestClient::RequestFailed => e
71
+ print STDERR, e.response.body
72
+ raise e
73
+ end
74
+ else
75
+ super
76
+ end
77
+ end
78
+
79
+ require 'irb'
80
+ require 'irb/completion'
81
+
82
+ if File.exists? ".irbrc"
83
+ ENV['IRBRC'] = ".irbrc"
84
+ end
85
+
86
+ if File.exists?(File.expand_path(rcfile = "~/.restclientrc"))
87
+ load(rcfile)
88
+ end
89
+
90
+ ARGV.clear
91
+
92
+ IRB.start
93
+ exit!