{"id":13427846,"url":"https://github.com/rest-client/rest-client","last_synced_at":"2025-05-14T08:05:04.359Z","repository":{"id":751412,"uuid":"404319","full_name":"rest-client/rest-client","owner":"rest-client","description":"Simple HTTP and REST client for Ruby, inspired by microframework syntax for specifying actions.","archived":false,"fork":false,"pushed_at":"2024-05-19T10:18:13.000Z","size":1458,"stargazers_count":5228,"open_issues_count":141,"forks_count":933,"subscribers_count":104,"default_branch":"master","last_synced_at":"2025-05-14T08:02:54.750Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://rubydoc.info/github/rest-client/rest-client/master","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rest-client.png","metadata":{"files":{"readme":"README.md","changelog":"history.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-12-07T19:34:29.000Z","updated_at":"2025-05-13T04:16:41.000Z","dependencies_parsed_at":"2024-06-17T16:30:48.052Z","dependency_job_id":"181cdd0f-c81a-42d4-b4a4-7bb666c311a6","html_url":"https://github.com/rest-client/rest-client","commit_stats":{"total_commits":850,"total_committers":112,"mean_commits":7.589285714285714,"dds":0.7352941176470589,"last_synced_commit":"2c72a2e77e2e87d25ff38feba0cf048d51bd5eca"},"previous_names":[],"tags_count":43,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rest-client%2Frest-client","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rest-client%2Frest-client/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rest-client%2Frest-client/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rest-client%2Frest-client/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rest-client","download_url":"https://codeload.github.com/rest-client/rest-client/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254101588,"owners_count":22014907,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T01:00:41.275Z","updated_at":"2025-05-14T08:05:04.338Z","avatar_url":"https://github.com/rest-client.png","language":"Ruby","readme":"# REST Client -- simple DSL for accessing HTTP and REST resources\n\n[![Gem Downloads](https://img.shields.io/gem/dt/rest-client.svg)](https://rubygems.org/gems/rest-client)\n[![Build Status](https://travis-ci.org/rest-client/rest-client.svg?branch=master)](https://travis-ci.org/rest-client/rest-client)\n[![Code Climate](https://codeclimate.com/github/rest-client/rest-client.svg)](https://codeclimate.com/github/rest-client/rest-client)\n[![Inline docs](http://inch-ci.org/github/rest-client/rest-client.svg?branch=master)](http://www.rubydoc.info/github/rest-client/rest-client/master)\n[![Join the chat at https://gitter.im/ruby-rest-client/community](https://badges.gitter.im/ruby-rest-client/community.svg)](https://gitter.im/ruby-rest-client/community?utm_source=badge\u0026utm_medium=badge\u0026utm_campaign=pr-badge\u0026utm_content=badge)\n\nA simple HTTP and REST client for Ruby, inspired by the Sinatra's microframework style\nof specifying actions: get, put, post, delete.\n\n* Main page: https://github.com/rest-client/rest-client\n* Mailing list: https://groups.io/g/rest-client\n\n### New mailing list\n\nWe have a new email list for announcements, hosted by Groups.io.\n\n* Subscribe on the web: https://groups.io/g/rest-client\n\n* Subscribe by sending an email: mailto:rest-client+subscribe@groups.io\n\n* Open discussion subgroup: https://groups.io/g/rest-client+discuss\n\nThe old Librelist mailing list is *defunct*, as Librelist appears to be broken\nand not accepting new mail. The old archives are still up, but have been\nimported into the new list archives as well.\nhttp://librelist.com/browser/rest.client\n\n## Requirements\n\nMRI Ruby 2.0 and newer are supported. Alternative interpreters compatible with\n2.0+ should work as well.\n\nEarlier Ruby versions such as 1.8.7, 1.9.2, and 1.9.3 are no longer supported. These\nversions no longer have any official support, and do not receive security\nupdates.\n\nThe rest-client gem depends on these other gems for usage at runtime:\n\n* [mime-types](http://rubygems.org/gems/mime-types)\n* [netrc](http://rubygems.org/gems/netrc)\n* [http-accept](https://rubygems.org/gems/http-accept)\n* [http-cookie](https://rubygems.org/gems/http-cookie)\n\nThere are also several development dependencies. It's recommended to use\n[bundler](http://bundler.io/) to manage these dependencies for hacking on\nrest-client.\n\n### Upgrading to rest-client 2.0 from 1.x\n\nUsers are encouraged to upgrade to rest-client 2.0, which cleans up a number of\nAPI warts and wrinkles, making rest-client generally more useful. Usage is\nlargely compatible, so many applications will be able to upgrade with no\nchanges.\n\nOverview of significant changes:\n\n* requires Ruby \u003e= 2.0\n* `RestClient::Response` objects are a subclass of `String` rather than a\n  Frankenstein monster. And `#body` or `#to_s` return a true `String` object.\n* cleanup of exception classes, including new `RestClient::Exceptions::Timeout`\n* improvements to handling of redirects: responses and history are properly\n  exposed\n* major changes to cookie support: cookie jars are used for browser-like\n  behavior throughout\n* encoding: Content-Type charset response headers are used to automatically set\n  the encoding of the response string\n* HTTP params: handling of GET/POST params is more consistent and sophisticated\n  for deeply nested hash objects, and `ParamsArray` can be used to pass ordered\n  params\n* improved proxy support with per-request proxy configuration, plus the ability\n  to disable proxies set by environment variables\n* default request headers: rest-client sets `Accept: */*` and\n  `User-Agent: rest-client/...`\n\nSee [history.md](./history.md) for a more complete description of changes.\n\n## Usage: Raw URL\n\nBasic usage:\n\n```ruby\nrequire 'rest-client'\n\nRestClient.get(url, headers={})\n\nRestClient.post(url, payload, headers={})\n```\n\nIn the high level helpers, only POST, PATCH, and PUT take a payload argument.\nTo pass a payload with other HTTP verbs or to pass more advanced options, use\n`RestClient::Request.execute` instead.\n\nMore detailed examples:\n\n```ruby\nrequire 'rest-client'\n\nRestClient.get 'http://example.com/resource'\n\nRestClient.get 'http://example.com/resource', {params: {id: 50, 'foo' =\u003e 'bar'}}\n\nRestClient.get 'https://user:password@example.com/private/resource', {accept: :json}\n\nRestClient.post 'http://example.com/resource', {param1: 'one', nested: {param2: 'two'}}\n\nRestClient.post \"http://example.com/resource\", {'x' =\u003e 1}.to_json, {content_type: :json, accept: :json}\n\nRestClient.delete 'http://example.com/resource'\n\n\u003e\u003e response = RestClient.get 'http://example.com/resource'\n=\u003e \u003cRestClient::Response 200 \"\u003c!doctype h...\"\u003e\n\u003e\u003e response.code\n=\u003e 200\n\u003e\u003e response.cookies\n=\u003e {\"Foo\"=\u003e\"BAR\", \"QUUX\"=\u003e\"QUUUUX\"}\n\u003e\u003e response.headers\n=\u003e {:content_type=\u003e\"text/html; charset=utf-8\", :cache_control=\u003e\"private\" ... }\n\u003e\u003e response.body\n=\u003e \"\u003c!doctype html\u003e\\n\u003chtml\u003e\\n\u003chead\u003e\\n    \u003ctitle\u003eExample Domain\u003c/title\u003e\\n\\n ...\"\n\nRestClient.post( url,\n  {\n    :transfer =\u003e {\n      :path =\u003e '/foo/bar',\n      :owner =\u003e 'that_guy',\n      :group =\u003e 'those_guys'\n    },\n     :upload =\u003e {\n      :file =\u003e File.new(path, 'rb')\n    }\n  })\n```\n## Passing advanced options\n\nThe top level helper methods like RestClient.get accept a headers hash as\ntheir last argument and don't allow passing more complex options. But these\nhelpers are just thin wrappers around `RestClient::Request.execute`.\n\n```ruby\nRestClient::Request.execute(method: :get, url: 'http://example.com/resource',\n                            timeout: 10)\n\nRestClient::Request.execute(method: :get, url: 'http://example.com/resource',\n                            ssl_ca_file: 'myca.pem',\n                            ssl_ciphers: 'AESGCM:!aNULL')\n```\nYou can also use this to pass a payload for HTTP verbs like DELETE, where the\n`RestClient.delete` helper doesn't accept a payload.\n\n```ruby\nRestClient::Request.execute(method: :delete, url: 'http://example.com/resource',\n                            payload: 'foo', headers: {myheader: 'bar'})\n```\n\nDue to unfortunate choices in the original API, the params used to populate the\nquery string are actually taken out of the headers hash. So if you want to pass\nboth the params hash and more complex options, use the special key\n`:params` in the headers hash. This design may change in a future major\nrelease.\n\n```ruby\nRestClient::Request.execute(method: :get, url: 'http://example.com/resource',\n                            timeout: 10, headers: {params: {foo: 'bar'}})\n\n➔ GET http://example.com/resource?foo=bar\n```\n\n## Multipart\n\nYeah, that's right!  This does multipart sends for you!\n\n```ruby\nRestClient.post '/data', :myfile =\u003e File.new(\"/path/to/image.jpg\", 'rb')\n```\n\nThis does two things for you:\n\n- Auto-detects that you have a File value sends it as multipart\n- Auto-detects the mime of the file and sets it in the HEAD of the payload for each entry\n\nIf you are sending params that do not contain a File object but the payload needs to be multipart then:\n\n```ruby\nRestClient.post '/data', {:foo =\u003e 'bar', :multipart =\u003e true}\n```\n\n## Usage: ActiveResource-Style\n\n```ruby\nresource = RestClient::Resource.new 'http://example.com/resource'\nresource.get\n\nprivate_resource = RestClient::Resource.new 'https://example.com/private/resource', 'user', 'pass'\nprivate_resource.put File.read('pic.jpg'), :content_type =\u003e 'image/jpg'\n```\n\nSee RestClient::Resource module docs for details.\n\n## Usage: Resource Nesting\n\n```ruby\nsite = RestClient::Resource.new('http://example.com')\nsite['posts/1/comments'].post 'Good article.', :content_type =\u003e 'text/plain'\n```\nSee `RestClient::Resource` docs for details.\n\n## Exceptions (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html)\n\n- for result codes between `200` and `207`, a `RestClient::Response` will be returned\n- for result codes `301`, `302` or `307`, the redirection will be followed if the request is a `GET` or a `HEAD`\n- for result code `303`, the redirection will be followed and the request transformed into a `GET`\n- for other cases, a `RestClient::ExceptionWithResponse` holding the Response will be raised; a specific exception class will be thrown for known error codes\n- call `.response` on the exception to get the server's response\n\n```ruby\n\u003e\u003e RestClient.get 'http://example.com/nonexistent'\nException: RestClient::NotFound: 404 Not Found\n\n\u003e\u003e begin\n     RestClient.get 'http://example.com/nonexistent'\n   rescue RestClient::ExceptionWithResponse =\u003e e\n     e.response\n   end\n=\u003e \u003cRestClient::Response 404 \"\u003c!doctype h...\"\u003e\n```\n\n### Other exceptions\n\nWhile most exceptions have been collected under `RestClient::RequestFailed` aka\n`RestClient::ExceptionWithResponse`, there are a few quirky exceptions that\nhave been kept for backwards compatibility.\n\nRestClient will propagate up exceptions like socket errors without modification:\n\n```ruby\n\u003e\u003e RestClient.get 'http://localhost:12345'\nException: Errno::ECONNREFUSED: Connection refused - connect(2) for \"localhost\" port 12345\n```\n\nRestClient handles a few specific error cases separately in order to give\nbetter error messages. These will hopefully be cleaned up in a future major\nrelease.\n\n`RestClient::ServerBrokeConnection` is translated from `EOFError` to give a\nbetter error message.\n\n`RestClient::SSLCertificateNotVerified` is raised when HTTPS validation fails.\nOther `OpenSSL::SSL::SSLError` errors are raised as is.\n\n### Redirection\n\nBy default, rest-client will follow HTTP 30x redirection requests.\n\n__New in 2.0:__ `RestClient::Response` exposes a `#history` method that returns\na list of each response received in a redirection chain.\n\n```ruby\n\u003e\u003e r = RestClient.get('http://httpbin.org/redirect/2')\n=\u003e \u003cRestClient::Response 200 \"{\\n  \\\"args\\\":...\"\u003e\n\n# see each response in the redirect chain\n\u003e\u003e r.history\n=\u003e [\u003cRestClient::Response 302 \"\u003c!DOCTYPE H...\"\u003e, \u003cRestClient::Response 302 \"\"\u003e]\n\n# see each requested URL\n\u003e\u003e r.request.url\n=\u003e \"http://httpbin.org/get\"\n\u003e\u003e r.history.map {|x| x.request.url}\n=\u003e [\"http://httpbin.org/redirect/2\", \"http://httpbin.org/relative-redirect/1\"]\n```\n\n#### Manually following redirection\n\nTo disable automatic redirection, set `:max_redirects =\u003e 0`.\n\n__New in 2.0:__ Prior versions of rest-client would raise\n`RestClient::MaxRedirectsReached`, with no easy way to access the server's\nresponse. In 2.0, rest-client raises the normal\n`RestClient::ExceptionWithResponse` as it would with any other non-HTTP-20x\nresponse.\n\n```ruby\n\u003e\u003e RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1')\n=\u003e RestClient::Response 200 \"{\\n  \"args\":...\"\n\n\u003e\u003e RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1', max_redirects: 0)\nRestClient::Found: 302 Found\n```\n\nTo manually follow redirection, you can call `Response#follow_redirection`. Or\nyou could of course inspect the result and choose custom behavior.\n\n```ruby\n\u003e\u003e RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1', max_redirects: 0)\nRestClient::Found: 302 Found\n\u003e\u003e begin\n       RestClient::Request.execute(method: :get, url: 'http://httpbin.org/redirect/1', max_redirects: 0)\n   rescue RestClient::ExceptionWithResponse =\u003e err\n   end\n\u003e\u003e err\n=\u003e #\u003cRestClient::Found: 302 Found\u003e\n\u003e\u003e err.response\n=\u003e RestClient::Response 302 \"\u003c!DOCTYPE H...\"\n\u003e\u003e err.response.headers[:location]\n=\u003e \"/get\"\n\u003e\u003e err.response.follow_redirection\n=\u003e RestClient::Response 200 \"{\\n  \"args\":...\"\n```\n\n## Result handling\n\nThe result of a `RestClient::Request` is a `RestClient::Response` object.\n\n__New in 2.0:__ `RestClient::Response` objects are now a subclass of `String`.\nPreviously, they were a real String object with response functionality mixed\nin, which was very confusing to work with.\n\nResponse objects have several useful methods. (See the class rdoc for more details.)\n\n- `Response#code`: The HTTP response code\n- `Response#body`: The response body as a string. (AKA .to_s)\n- `Response#headers`: A hash of HTTP response headers\n- `Response#raw_headers`: A hash of HTTP response headers as unprocessed arrays\n- `Response#cookies`: A hash of HTTP cookies set by the server\n- `Response#cookie_jar`: \u003cem\u003eNew in 1.8\u003c/em\u003e An HTTP::CookieJar of cookies\n- `Response#request`: The RestClient::Request object used to make the request\n- `Response#history`: \u003cem\u003eNew in 2.0\u003c/em\u003e If redirection was followed, a list of prior Response objects\n\n```ruby\nRestClient.get('http://example.com')\n➔ \u003cRestClient::Response 200 \"\u003c!doctype h...\"\u003e\n\nbegin\n RestClient.get('http://example.com/notfound')\nrescue RestClient::ExceptionWithResponse =\u003e err\n  err.response\nend\n➔ \u003cRestClient::Response 404 \"\u003c!doctype h...\"\u003e\n```\n\n### Response callbacks, error handling\n\nA block can be passed to the RestClient method. This block will then be called with the Response.\nResponse.return! can be called to invoke the default response's behavior.\n\n```ruby\n# Don't raise exceptions but return the response\n\u003e\u003e RestClient.get('http://example.com/nonexistent') {|response, request, result| response }\n=\u003e \u003cRestClient::Response 404 \"\u003c!doctype h...\"\u003e\n```\n\n```ruby\n# Manage a specific error code\nRestClient.get('http://example.com/resource') { |response, request, result, \u0026block|\n  case response.code\n  when 200\n    p \"It worked !\"\n    response\n  when 423\n    raise SomeCustomExceptionIfYouWant\n  else\n    response.return!(\u0026block)\n  end\n}\n```\n\nBut note that it may be more straightforward to use exceptions to handle\ndifferent HTTP error response cases:\n\n```ruby\nbegin\n  resp = RestClient.get('http://example.com/resource')\nrescue RestClient::Unauthorized, RestClient::Forbidden =\u003e err\n  puts 'Access denied'\n  return err.response\nrescue RestClient::ImATeapot =\u003e err\n  puts 'The server is a teapot! # RFC 2324'\n  return err.response\nelse\n  puts 'It worked!'\n  return resp\nend\n```\n\nFor GET and HEAD requests, rest-client automatically follows redirection. For\nother HTTP verbs, call `.follow_redirection` on the response object (works both\nin block form and in exception form).\n\n```ruby\n# Follow redirections for all request types and not only for get and head\n# RFC : \"If the 301, 302 or 307 status code is received in response to a request other than GET or HEAD,\n#        the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user,\n#        since this might change the conditions under which the request was issued.\"\n\n# block style\nRestClient.post('http://example.com/redirect', 'body') { |response, request, result|\n  case response.code\n  when 301, 302, 307\n    response.follow_redirection\n  else\n    response.return!\n  end\n}\n\n# exception style by explicit classes\nbegin\n  RestClient.post('http://example.com/redirect', 'body')\nrescue RestClient::MovedPermanently,\n       RestClient::Found,\n       RestClient::TemporaryRedirect =\u003e err\n  err.response.follow_redirection\nend\n\n# exception style by response code\nbegin\n  RestClient.post('http://example.com/redirect', 'body')\nrescue RestClient::ExceptionWithResponse =\u003e err\n  case err.http_code\n  when 301, 302, 307\n    err.response.follow_redirection\n  else\n    raise\n  end\nend\n```\n\n## Non-normalized URIs\n\nIf you need to normalize URIs, e.g. to work with International Resource Identifiers (IRIs),\nuse the Addressable gem (https://github.com/sporkmonger/addressable/) in your code:\n\n```ruby\n  require 'addressable/uri'\n  RestClient.get(Addressable::URI.parse(\"http://www.詹姆斯.com/\").normalize.to_str)\n```\n\n## Lower-level access\n\nFor cases not covered by the general API, you can use the `RestClient::Request` class, which provides a lower-level API.\n\nYou can:\n\n- specify ssl parameters\n- override cookies\n- manually handle the response (e.g. to operate on it as a stream rather than reading it all into memory)\n\nSee `RestClient::Request`'s documentation for more information.\n\n### Streaming request payload\n\nRestClient will try to stream any file-like payload rather than reading it into\nmemory. This happens through `RestClient::Payload::Streamed`, which is\nautomatically called internally by `RestClient::Payload.generate` on anything\nwith a `read` method.\n\n```ruby\n\u003e\u003e r = RestClient.put('http://httpbin.org/put', File.open('/tmp/foo.txt', 'r'),\n                      content_type: 'text/plain')\n=\u003e \u003cRestClient::Response 200 \"{\\n  \\\"args\\\":...\"\u003e\n```\n\nIn Multipart requests, RestClient will also stream file handles passed as Hash\n(or __new in 2.1__ ParamsArray).\n\n```ruby\n\u003e\u003e r = RestClient.put('http://httpbin.org/put',\n                      {file_a: File.open('a.txt', 'r'),\n                       file_b: File.open('b.txt', 'r')})\n=\u003e \u003cRestClient::Response 200 \"{\\n  \\\"args\\\":...\"\u003e\n\n# received by server as two file uploads with multipart/form-data\n\u003e\u003e JSON.parse(r)['files'].keys\n=\u003e ['file_a', 'file_b']\n```\n\n### Streaming responses\n\nNormally, when you use `RestClient.get` or the lower level\n`RestClient::Request.execute method: :get` to retrieve data, the entire\nresponse is buffered in memory and returned as the response to the call.\n\nHowever, if you are retrieving a large amount of data, for example a Docker\nimage, an iso, or any other large file, you may want to stream the response\ndirectly to disk rather than loading it in memory. If you have a very large\nfile, it may become *impossible* to load it into memory.\n\nThere are two main ways to do this:\n\n#### `raw_response`, saves into Tempfile\n\nIf you pass `raw_response: true` to `RestClient::Request.execute`, it will save\nthe response body to a temporary file (using `Tempfile`) and return a\n`RestClient::RawResponse` object rather than a `RestClient::Response`.\n\nNote that the tempfile created by `Tempfile.new` will be in `Dir.tmpdir`\n(usually `/tmp/`), which you can override to store temporary files in a\ndifferent location. This file will be unlinked when it is dereferenced.\n\nIf logging is enabled, this will also print download progress.\n__New in 2.1:__ Customize the interval with `:stream_log_percent` (defaults to\n10 for printing a message every 10% complete).\n\nFor example:\n\n```ruby\n\u003e\u003e raw = RestClient::Request.execute(\n           method: :get,\n           url: 'http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-desktop-amd64.iso',\n           raw_response: true)\n=\u003e \u003cRestClient::RawResponse @code=200, @file=#\u003cTempfile:/tmp/rest-client.20170522-5346-1pptjm1\u003e, @request=\u003cRestClient::Request @method=\"get\", @url=\"http://releases.ubuntu.com/16.04.2/ubuntu-16.04.2-desktop-amd64.iso\"\u003e\u003e\n\u003e\u003e raw.file.size\n=\u003e 1554186240\n\u003e\u003e raw.file.path\n=\u003e \"/tmp/rest-client.20170522-5346-1pptjm1\"\nraw.file.path\n=\u003e \"/tmp/rest-client.20170522-5346-1pptjm1\"\n\n\u003e\u003e require 'digest/sha1'\n\u003e\u003e Digest::SHA1.file(raw.file.path).hexdigest\n=\u003e \"4375b73e3a1aa305a36320ffd7484682922262b3\"\n```\n\n#### `block_response`, receives raw Net::HTTPResponse\n\nIf you want to stream the data from the response to a file as it comes, rather\nthan entirely in memory, you can also pass `RestClient::Request.execute` a\nparameter `:block_response` to which you pass a block/proc. This block receives\nthe raw unmodified Net::HTTPResponse object from Net::HTTP, which you can use\nto stream directly to a file as each chunk is received.\n\nNote that this bypasses all the usual HTTP status code handling, so you will\nwant to do you own checking for HTTP 20x response codes, redirects, etc.\n\nThe following is an example:\n\n````ruby\nFile.open('/some/output/file', 'w') {|f|\n  block = proc { |response|\n    response.read_body do |chunk|\n      f.write chunk\n    end\n  }\n  RestClient::Request.execute(method: :get,\n                              url: 'http://example.com/some/really/big/file.img',\n                              block_response: block)\n}\n````\n\n## Shell\n\nThe restclient shell command gives an IRB session with RestClient already loaded:\n\n```ruby\n$ restclient\n\u003e\u003e RestClient.get 'http://example.com'\n```\n\nSpecify a URL argument for get/post/put/delete on that resource:\n\n```ruby\n$ restclient http://example.com\n\u003e\u003e put '/resource', 'data'\n```\n\nAdd a user and password for authenticated resources:\n\n```ruby\n$ restclient https://example.com user pass\n\u003e\u003e delete '/private/resource'\n```\n\nCreate ~/.restclient for named sessions:\n\n```ruby\n  sinatra:\n    url: http://localhost:4567\n  rack:\n    url: http://localhost:9292\n  private_site:\n    url: http://example.com\n    username: user\n    password: pass\n```\n\nThen invoke:\n\n```ruby\n$ restclient private_site\n```\n\nUse as a one-off, curl-style:\n\n```ruby\n$ restclient get http://example.com/resource \u003e output_body\n\n$ restclient put http://example.com/resource \u003c input_body\n```\n\n## Logging\n\nTo enable logging globally you can:\n\n- set RestClient.log with a Ruby Logger\n\n```ruby\nRestClient.log = STDOUT\n```\n\n- or set an environment variable to avoid modifying the code (in this case you can use a file name, \"stdout\" or \"stderr\"):\n\n```ruby\n$ RESTCLIENT_LOG=stdout path/to/my/program\n```\n\nYou can also set individual loggers when instantiating a Resource or making an\nindividual request:\n\n```ruby\nresource = RestClient::Resource.new 'http://example.com/resource', log: Logger.new(STDOUT)\n```\n\n```ruby\nRestClient::Request.execute(method: :get, url: 'http://example.com/foo', log: Logger.new(STDERR))\n```\n\nAll options produce logs like this:\n\n```ruby\nRestClient.get \"http://some/resource\"\n# =\u003e 200 OK | text/html 250 bytes\nRestClient.put \"http://some/resource\", \"payload\"\n# =\u003e 401 Unauthorized | application/xml 340 bytes\n```\n\nNote that these logs are valid Ruby, so you can paste them into the `restclient`\nshell or a script to replay your sequence of rest calls.\n\n## Proxy\n\nAll calls to RestClient, including Resources, will use the proxy specified by\n`RestClient.proxy`:\n\n```ruby\nRestClient.proxy = \"http://proxy.example.com/\"\nRestClient.get \"http://some/resource\"\n# =\u003e response from some/resource as proxied through proxy.example.com\n```\n\nOften the proxy URL is set in an environment variable, so you can do this to\nuse whatever proxy the system is configured to use:\n\n```ruby\n  RestClient.proxy = ENV['http_proxy']\n```\n\n__New in 2.0:__ Specify a per-request proxy by passing the :proxy option to\nRestClient::Request. This will override any proxies set by environment variable\nor by the global `RestClient.proxy` value.\n\n```ruby\nRestClient::Request.execute(method: :get, url: 'http://example.com',\n                            proxy: 'http://proxy.example.com')\n# =\u003e single request proxied through the proxy\n```\n\nThis can be used to disable the use of a proxy for a particular request.\n\n```ruby\nRestClient.proxy = \"http://proxy.example.com/\"\nRestClient::Request.execute(method: :get, url: 'http://example.com', proxy: nil)\n# =\u003e single request sent without a proxy\n```\n\n## Query parameters\n\nRest-client can render a hash as HTTP query parameters for GET/HEAD/DELETE\nrequests or as HTTP post data in `x-www-form-urlencoded` format for POST\nrequests.\n\n__New in 2.0:__ Even though there is no standard specifying how this should\nwork, rest-client follows a similar convention to the one used by Rack / Rails\nservers for handling arrays, nested hashes, and null values.\n\nThe implementation in\n[./lib/rest-client/utils.rb](RestClient::Utils.encode_query_string)\nclosely follows\n[Rack::Utils.build_nested_query](http://www.rubydoc.info/gems/rack/Rack/Utils#build_nested_query-class_method),\nbut treats empty arrays and hashes as `nil`. (Rack drops them entirely, which\nis confusing behavior.)\n\nIf you don't like this behavior and want more control, just serialize params\nyourself (e.g. with `URI.encode_www_form`) and add the query string to the URL\ndirectly for GET parameters or pass the payload as a string for POST requests.\n\nBasic GET params:\n```ruby\nRestClient.get('https://httpbin.org/get', params: {foo: 'bar', baz: 'qux'})\n# GET \"https://httpbin.org/get?foo=bar\u0026baz=qux\"\n```\n\nBasic `x-www-form-urlencoded` POST params:\n```ruby\n\u003e\u003e r = RestClient.post('https://httpbin.org/post', {foo: 'bar', baz: 'qux'})\n# POST \"https://httpbin.org/post\", data: \"foo=bar\u0026baz=qux\"\n=\u003e \u003cRestClient::Response 200 \"{\\n  \\\"args\\\":...\"\u003e\n\u003e\u003e JSON.parse(r.body)\n=\u003e {\"args\"=\u003e{},\n    \"data\"=\u003e\"\",\n    \"files\"=\u003e{},\n    \"form\"=\u003e{\"baz\"=\u003e\"qux\", \"foo\"=\u003e\"bar\"},\n    \"headers\"=\u003e\n    {\"Accept\"=\u003e\"*/*\",\n        \"Accept-Encoding\"=\u003e\"gzip, deflate\",\n        \"Content-Length\"=\u003e\"15\",\n        \"Content-Type\"=\u003e\"application/x-www-form-urlencoded\",\n        \"Host\"=\u003e\"httpbin.org\"},\n    \"json\"=\u003enil,\n    \"url\"=\u003e\"https://httpbin.org/post\"}\n```\n\nJSON payload: rest-client does not speak JSON natively, so serialize your\npayload to a string before passing it to rest-client.\n```ruby\n\u003e\u003e payload = {'name' =\u003e 'newrepo', 'description': 'A new repo'}\n\u003e\u003e RestClient.post('https://api.github.com/user/repos', payload.to_json, content_type: :json)\n=\u003e \u003cRestClient::Response 201 \"{\\\"id\\\":75149...\"\u003e\n```\n\nAdvanced GET params (arrays):\n```ruby\n\u003e\u003e r = RestClient.get('https://http-params.herokuapp.com/get', params: {foo: [1,2,3]})\n# GET \"https://http-params.herokuapp.com/get?foo[]=1\u0026foo[]=2\u0026foo[]=3\"\n=\u003e \u003cRestClient::Response 200 \"Method: GET...\"\u003e\n\u003e\u003e puts r.body\nquery_string: \"foo[]=1\u0026foo[]=2\u0026foo[]=3\"\ndecoded:      \"foo[]=1\u0026foo[]=2\u0026foo[]=3\"\n\nGET:\n  {\"foo\"=\u003e[\"1\", \"2\", \"3\"]}\n```\n\nAdvanced GET params (nested hashes):\n```ruby\n\u003e\u003e r = RestClient.get('https://http-params.herokuapp.com/get', params: {outer: {foo: 123, bar: 456}})\n# GET \"https://http-params.herokuapp.com/get?outer[foo]=123\u0026outer[bar]=456\"\n=\u003e \u003cRestClient::Response 200 \"Method: GET...\"\u003e\n\u003e\u003e puts r.body\n...\nquery_string: \"outer[foo]=123\u0026outer[bar]=456\"\ndecoded:      \"outer[foo]=123\u0026outer[bar]=456\"\n\nGET:\n  {\"outer\"=\u003e{\"foo\"=\u003e\"123\", \"bar\"=\u003e\"456\"}}\n```\n\n__New in 2.0:__ The new `RestClient::ParamsArray` class allows callers to\nprovide ordering even to structured parameters. This is useful for unusual\ncases where the server treats the order of parameters as significant or you\nwant to pass a particular key multiple times.\n\nMultiple fields with the same name using ParamsArray:\n```ruby\n\u003e\u003e RestClient.get('https://httpbin.org/get', params:\n                  RestClient::ParamsArray.new([[:foo, 1], [:foo, 2]]))\n# GET \"https://httpbin.org/get?foo=1\u0026foo=2\"\n```\n\nNested ParamsArray:\n```ruby\n\u003e\u003e RestClient.get('https://httpbin.org/get', params:\n                  {foo: RestClient::ParamsArray.new([[:a, 1], [:a, 2]])})\n# GET \"https://httpbin.org/get?foo[a]=1\u0026foo[a]=2\"\n```\n\n## Headers\n\nRequest headers can be set by passing a ruby hash containing keys and values\nrepresenting header names and values:\n\n```ruby\n# GET request with modified headers\nRestClient.get 'http://example.com/resource', {:Authorization =\u003e 'Bearer cT0febFoD5lxAlNAXHo6g'}\n\n# POST request with modified headers\nRestClient.post 'http://example.com/resource', {:foo =\u003e 'bar', :baz =\u003e 'qux'}, {:Authorization =\u003e 'Bearer cT0febFoD5lxAlNAXHo6g'}\n\n# DELETE request with modified headers\nRestClient.delete 'http://example.com/resource', {:Authorization =\u003e 'Bearer cT0febFoD5lxAlNAXHo6g'}\n```\n\n## Timeouts\n\nBy default the timeout for a request is 60 seconds. Timeouts for your request can\nbe adjusted by setting the `timeout:` to the number of seconds that you would like\nthe request to wait. Setting `timeout:` will override both `read_timeout:` and `open_timeout:`.\n\n```ruby\nRestClient::Request.execute(method: :get, url: 'http://example.com/resource',\n                            timeout: 120)\n```\n\nAdditionally, you can set `read_timeout:` and `open_timeout:` separately.\n\n```ruby\nRestClient::Request.execute(method: :get, url: 'http://example.com/resource',\n                            read_timeout: 120, open_timeout: 240)\n```\n\n## Cookies\n\nRequest and Response objects know about HTTP cookies, and will automatically\nextract and set headers for them as needed:\n\n```ruby\nresponse = RestClient.get 'http://example.com/action_which_sets_session_id'\nresponse.cookies\n# =\u003e {\"_applicatioN_session_id\" =\u003e \"1234\"}\n\nresponse2 = RestClient.post(\n  'http://localhost:3000/',\n  {:param1 =\u003e \"foo\"},\n  {:cookies =\u003e {:session_id =\u003e \"1234\"}}\n)\n# ...response body\n```\n### Full cookie jar support (new in 1.8)\n\nThe original cookie implementation was very naive and ignored most of the\ncookie RFC standards.\n__New in 1.8__:  An HTTP::CookieJar of cookies\n\nResponse objects now carry a cookie_jar method that exposes an HTTP::CookieJar\nof cookies, which supports full standards compliant behavior.\n\n## SSL/TLS support\n\nVarious options are supported for configuring rest-client's TLS settings. By\ndefault, rest-client will verify certificates using the system's CA store on\nall platforms. (This is intended to be similar to how browsers behave.) You can\nspecify an :ssl_ca_file, :ssl_ca_path, or :ssl_cert_store to customize the\ncertificate authorities accepted.\n\n### SSL Client Certificates\n\n```ruby\nRestClient::Resource.new(\n  'https://example.com',\n  :ssl_client_cert  =\u003e  OpenSSL::X509::Certificate.new(File.read(\"cert.pem\")),\n  :ssl_client_key   =\u003e  OpenSSL::PKey::RSA.new(File.read(\"key.pem\"), \"passphrase, if any\"),\n  :ssl_ca_file      =\u003e  \"ca_certificate.pem\",\n  :verify_ssl       =\u003e  OpenSSL::SSL::VERIFY_PEER\n).get\n```\nSelf-signed certificates can be generated with the openssl command-line tool.\n\n## Hook\n\nRestClient.add_before_execution_proc add a Proc to be called before each execution.\nIt's handy if you need direct access to the HTTP request.\n\nExample:\n\n```ruby\n# Add oauth support using the oauth gem\nrequire 'oauth'\naccess_token = ...\n\nRestClient.add_before_execution_proc do |req, params|\n  access_token.sign! req\nend\n\nRestClient.get 'http://example.com'\n```\n\n## More\n\nNeed caching, more advanced logging or any ability provided by Rack middleware?\n\nHave a look at rest-client-components: http://github.com/crohr/rest-client-components\n\n## Credits\n| | |\n|-------------------------|---------------------------------------------------------|\n| **REST Client Team**    | Andy Brody                                              |\n| **Creator**             | Adam Wiggins                                            |\n| **Maintainers Emeriti** | Lawrence Leonard Gilbert, Matthew Manning, Julien Kirch |\n| **Major contributions** | Blake Mizerany, Julien Kirch                            |\n\nA great many generous folks have contributed features and patches.\nSee AUTHORS for the full list.\n\n## Legal\n\nReleased under the MIT License: https://opensource.org/licenses/MIT\n\nPhoto of the International Space Station was produced by NASA and is in the\npublic domain.\n\nCode for reading Windows root certificate store derived from work by Puppet;\nused under terms of the Apache License, Version 2.0.\n","funding_links":[],"categories":["API","Web Apps, Services \u0026 Interaction","Ruby","Clients","Http","HTTP","API Client Development Tools","HTTP Clients and tools","HTTP Clients"],"sub_categories":["Omniauth","HTTP clients","Ruby Clients","Ruby"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frest-client%2Frest-client","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frest-client%2Frest-client","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frest-client%2Frest-client/lists"}