A simple HTTP client.
Features:
- Supports Gzip|Deflate response
- Automatically parses JSON, HTML and XML responses
- Automatically follows redirect
Add this line to your application's Gemfile:
gem"aitch"And then execute:
$ bundle
Or install it yourself as:
$ gem install aitch
These are the default settings:
Aitch.configuredo |config|
# Set request timeout.config.timeout=5# Set default headers.config.default_headers={}# Set number of retries.# See Net::HTTP#max_retries to know which errors trigger a new request# attempt.config.retries=1# Set follow redirect.config.follow_redirect=true# Set redirection limit.config.redirect_limit=5# Set the user agent.config.user_agent="Aitch/0.0.1 (http://rubygems.org/gems/aitch)"# Set the logger.config.logger=nil# Set the base url.config.base_url=nilendPerforming requests:
response=Aitch.get("http://example.org",params,headers,options)Aitch.post("http://example.org",params,headers,options)Aitch.put("http://example.org",params,headers,options)Aitch.patch("http://example.org",params,headers,options)Aitch.delete("http://example.org",params,headers,options)Aitch.options("http://example.org",params,headers,options)Aitch.trace("http://example.org",params,headers,options)Aitch.head("http://example.org",params,headers,options)You can also use a DSL.
response=Aitch.getdourl"http://simplesideias.com.br"headersAuthorization: "Token token=abc"optionsfollow_redirect: falseparamsa: 1,b: 2endFinally, you can use keyword arguments:
Aitch.get(url: "http://example.org",params: {a: 1,b: 2},headers: {Authorization: "Token token=abc"},options: {follow_redirect: false})The response object:
response.html?response.xml?response.json?response.content_typeresponse.headersresponse.locationresponse.success?# status >= 200 && status <= 399response.redirect?# status 3xxresponse.error?# status 4xx or 5xxresponse.error# response errorresponse.body# returned bodyresponse.data# Parsed response bodyIf your response is a JSON, XML or a HTML content type, we'll automatically convert the response into the appropriate object.
response=Aitch.get("http://simplesideias.com.br")response.data.class#=> Nokogiri::HTML::Documentresponse.data.css("h1").size#=> 69response=Aitch.get("http://simplesideias.com.br/feed")response.data.class#=> Nokogiri::XML::Documentresponse.data.css("item").size#=> 10response=Aitch.get("https://api.github.com/users/fnando")response.data.class#=> Hashresponse.data["login"]#=> fnandoThe configuration:
Aitch.configuredo |config|
config.follow_redirect=trueconfig.redirect_limit=10endThe request:
Aitch.get("http://example.org")If the redirect limit is exceeded, then the Aitch::TooManyRedirectsError
exception is raised.
Setting basic auth credentials:
response=Aitch.getdourl"http://restrict.example.org/"optionsuser: "john",password: "test"endAitch.getdourl"http://example.org"headers"User-Agent"=>"MyBot/1.0.0"endThe header value can be a callable object.
Aitch.configuredo |config|
config.default_headers={"Authorization"=>->{"Token token=#{ENV.fetch("API_TOKEN")}"}}endSometimes you don't want to use the global settings (maybe you're building a lib). In this case, you can instantiate the namespace.
Request=Aitch::Namespace.newRequest.configuredo |config|
config.user_agent="MyLib/1.0.0"endRequest.get("http://example.org")When you know the kind of response you're expecting, you can validate it by
specifying the expect option.
Aitch.getdourl"http://example.org"optionsexpect: 200endIf this request receives anything other than 200, it will raise a
Aitch::StatusCodeError exception.
Expect(200 OK) <=> Actual(404 Not Found)
You can also provide a list of accepted statuses, like expect: [200, 201].
You can register new response parsers by using
Aitch::ResponseParser.register(name, parser), where parser must implement the
methods match?(content_type) and load(response_body). This is how you could
load CSV values.
require"csv"moduleCSVParserdefself.type:csvenddefself.match?(content_type)content_type.to_s =~ /csv/enddefself.load(source)CSV.parse(source.to_s)endendAitch::ResponseParser.prepend(:csv,CSVParser)The default behavior is returning the response body. You can replace it as the following:
moduleDefaultParserdefself.type:defaultenddefself.match?(content_type)trueenddefself.load(source)source.to_sendend# You should use append here, to ensure# that is that last parser on the list.Aitch::ResponseParser.append(:default,DefaultParser)Aitch comes with response parsers for HTML, XML and JSON.
By default, the JSON parser will be JSON. To set it to something else, use
Aitch::ResponseParser::JSONParser.engine.
require"oj"Aitch::ResponseParser::JSONParser.engine=OjWhen you're creating a wrapper for an API, usually the hostname is the same for
the whole API. In this case, you can avoid having to pass it around all the time
by setting Aitch::Configuration#base_url. This option is meant to be used when
you instantiate a new namespace.
Client=Aitch::Namespace.newClient.configuredo |config|
config.base_url="https://api.example.com"endClient.get("/users")- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request