Ruby


Installing

Requirements: Ruby >= 2.0
To utilize unirest, install the unirest gem:

Shell
gem install unirest

After installing the gem package you can now begin to simplifying requests by requiring unirest:

Ruby
require 'unirest'

response = Unirest.post API_URL,
  headers:{
    "X-Mashape-Key" => API_KEY,
    "Content-Type" => "application/x-www-form-urlencoded"
  },
  parameters:{
    "parameter" => "value"
  }

response.code # Status code
response.headers # Response headers
response.body # Parsed body
response.raw_body # Unparsed body
Asynchronous Requests

Unirest-Ruby also supports asynchronous requests with a callback function specified inside a block, like:

Ruby
require 'unirest'

response = Unirest.post API_URL,
  headers:{
    "X-Mashape-Key" => API_KEY,
    "Content-Type" => "application/x-www-form-urlencoded"
  },
  parameters:{
    "parameter" => "value"
  } {|response|
    response.code # Status code
    response.headers # Response headers
    response.body # Parsed body
    response.raw_body # Unparsed body
  }
File Uploads
Ruby
require 'unirest'

response = Unirest.post API_URL,
  headers:{
    "X-Mashape-Key" => API_KEY
  },
  parameters:{
    "content" => File.new("/path/to/file", "rb")
  }

Advanced Configuration

You can set some advanced configuration to tune Unirest-Ruby:

Timeout

You can set a custom timeout value (in seconds):

Ruby
Unirest.timeout(5) # 5s timeout
Default Request Headers

You can set default headers that will be sent on every request:

Ruby
Unirest.default_header('Header1','Value1')
Unirest.default_header('Header2','Value2')

You can clear the default headers anytime with:

Ruby
Unirest.clear_default_headers()
User-Agent

The default User-Agent string is unirest-ruby/1.1. You can customize it like this:

Ruby
Unirest.user_agent("custom_user_agent")