Installing
Requirements: Ruby >= 2.0
To utilize unirest, install the unirest gem:
gem install unirest
After installing the gem package you can now begin to simplifying requests by requiring unirest:
require 'unirest'
response = Unirest.post API_URL,
headers:{
"X-RapidAPI-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:
require 'unirest'
response = Unirest.post API_URL,
headers:{
"X-RapidAPI-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
require 'unirest'
response = Unirest.post API_URL,
headers:{
"X-RapidAPI-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):
Unirest.timeout(5) # 5s timeout
Default Request Headers
You can set default headers that will be sent on every request:
Unirest.default_header('Header1','Value1')
Unirest.default_header('Header2','Value2')
You can clear the default headers anytime with:
Unirest.clear_default_headers()
User-Agent
The default User-Agent string is unirest-ruby/1.1. You can customize it like this:
Unirest.user_agent("custom_user_agent")
Updated about a year ago