Giter VIP home page Giter VIP logo

unirest-ruby's Introduction

Unirest for Ruby Build Status version

License Downloads Code Climate Gitter

Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain the open-source API Gateway Kong.

Features

  • Make GET, POST, PUT, PATCH, DELETE requests
  • Both syncronous and asynchronous (non-blocking) requests
  • Supports form parameters, file uploads and custom body entities
  • Supports gzip
  • Supports Basic Authentication natively
  • Customizable timeout
  • Customizable default headers for every request (DRY)
  • Automatic JSON parsing into a native object for JSON responses

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'

Creating Requests

So you're probably wondering how using Unirest makes creating requests in Ruby easier, let's start with a working example:

response = Unirest.post "http://httpbin.org/post", 
                        headers:{ "Accept" => "application/json" }, 
                        parameters:{ :age => 23, :foo => "bar" }

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:

response = Unirest.post "http://httpbin.org/post", 
                        headers:{ "Accept" => "application/json" }, 
                        parameters:{ :age => 23, :foo => "bar" } {|response|
	response.code # Status code
	response.headers # Response headers
	response.body # Parsed body
	response.raw_body # Unparsed body
}

File Uploads

response = Unirest.post "http://httpbin.org/post", 
                        headers:{ "Accept" => "application/json" }, 
                        parameters:{ :age => 23, :file => File.new("/path/to/file", 'rb') }

Custom Entity Body

response = Unirest.post "http://httpbin.org/post", 
                        headers:{ "Accept" => "application/json" }, 
                        parameters:{ :age => "value", :foo => "bar" }.to_json # Converting the Hash to a JSON string

Basic Authentication

Authenticating the request with basic authentication can be done by providing an auth Hash with :user and :password keys like:

response = Unirest.get "http://httpbin.org/get", auth:{:user=>"username", :password=>"password"}

Request

Unirest.get(url, headers: {}, parameters: nil, auth:nil, &callback)
Unirest.post(url, headers: {}, parameters: nil, auth:nil, &callback)
Unirest.delete(url, headers: {}, parameters: nil, auth:nil, &callback)
Unirest.put(url, headers: {}, parameters: nil, auth:nil, &callback)
Unirest.patch(url, headers: {}, parameters: nil, auth:nil, &callback)
  • url (String) - Endpoint, address, or uri to be acted upon and requested information from.
  • headers (Object) - Request Headers as associative array or object
  • parameters (Array | Object | String) - Request Body associative array or object
  • callback (Function) - Optional; Asychronous callback method to be invoked upon result.

Response

Upon receiving a response Unirest returns the result in the form of an Object, this object should always have the same keys for each language regarding to the response details.

  • code - HTTP Response Status Code (Example 200)
  • headers - HTTP Response Headers
  • body - Parsed response body where applicable, for example JSON responses are parsed to Objects / Associative Arrays.
  • raw_body - Un-parsed response body

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")

Made with ♥ from the Mashape team

unirest-ruby's People

Contributors

esseguin avatar guizmaii avatar halostatue avatar hughbien avatar mxlje avatar nddrylliog avatar nijikokun avatar nikz avatar santyprada avatar shatsar avatar sonicaghi avatar stevenkaras avatar subnetmarco avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unirest-ruby's Issues

Add base_url method

Please, add base_url method, a-la on Airborne.

Airborne

Airborne.configure do |config|
  config.base_url = 'http://example.com/api/v1'
  config.headers = { 'x-auth-token' => 'my_token' }
end

Unirest

Unirest.base_url = 'http://example.com/api'
# http://example.com/api/auth?user=foo&pass=bar
response = Unirest.get '/auth?user=foo&pass=bar' 

Unable to activate unirest

When trying to run a script using Unirest I am getting the following error:

C:/Ruby24/lib/ruby/2.4.0/rubygems/specification.rb:2291:in 'raise_if_conflicts': Unable to activate unirest-1.1.2, because json-2.0.2 conflicts with json (~> 1.8.1) (Gem::ConflictError)

Getting this error on both Mac and PC. Any quick fix for this?

Disable automatically added square brackets at end of array name

Say I want to post an array of data to a remote source:

    array = [1,2,3]
    Unirest.post "https://www.my-website.com", parameters: { data: array }

When I receive the HTTP request on my-website.com, the body of the POST looks like this: data[]=1&data[]=2&data[]=3

According to this StackOverflow post, those square brackets are a convention to "address a limitation of PHP, which doesn't generate an array automatically if multiple values with the same name are submitted". All well and good if I'm posting to a PHP server, but if I'm posting to a different kind of server (in my case NancyFx), I can't easily get that data into an array.

I think it would make sense to get rid of these brackets by default and allow developers using unirest-ruby to post to a PHP server to do something like this:

    array = [1,2,3]
    Unirest.post "https://www.my-website.com", parameters: { "data[]": array }

Impossible to detect redirect

Some server returns code 301, but Unirest redirects it and returns code 200.

The correct behavior of returning code 301

$ curl --head http://httpbin.org/status/301 | head -n 1
HTTP/1.1 301 MOVED PERMANENTLY

The incorrect behavior of returning code 200

$ ruby -r unirest -e 'puts Unirest.get("http://httpbin.org/status/301").code'
200

How can I fix it?

11/13 tests fail on ruby 2.0p247

sevenspaces-3:~ corprew$ mkdir demo
sevenspaces-3:~ corprew$ cd demo
sevenspaces-3:demo corprew$ git clone https://github.com/Mashape/unirest-ruby.git
Cloning into 'unirest-ruby'...
remote: Counting objects: 489, done.
remote: Total 489 (delta 0), reused 0 (delta 0)
Receiving objects: 100% (489/489), 87.12 KiB | 0 bytes/s, done.
Resolving deltas: 100% (210/210), done.
Checking connectivity... done.
sevenspaces-3:demo corprew$ cd unirest-ruby
sevenspaces-3:unirest-ruby (master)corprew$ rake test
/Users/corprew/.rvm/rubies/ruby-2.0.0-p247/bin/ruby -I"lib:test" -I"/Users/corprew/.rvm/gems/ruby-2.0.0-p247/gems/rake-10.4.2/lib" "/Users/corprew/.rvm/gems/ruby-2.0.0-p247/gems/rake-10.4.2/lib/rake/rake_test_loader.rb" "test/unirest_test.rb"
/Users/corprew/.rvm/gems/ruby-2.0.0-p247/gems/minitest-5.4.0/lib/minitest/assertions.rb:15: warning: already initialized constant MiniTest::Assertions::UNDEFINED
/Users/corprew/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/minitest/unit.rb:79: warning: previous definition of UNDEFINED was here
Run options:

# Running tests:

[ 1/13] Unirest::RequestsTest#test_: Unirest::Requests should Basic Authentication.  = 0.28 s
  1) Error:
test_: Unirest::Requests should Basic Authentication. (Unirest::RequestsTest):
NoMethodError: undefined method `assertions' for #<Unirest::RequestsTest:0x007fbfba0af8d0>
    /Users/corprew/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/test/unit/assertions.rb:38:in `assert'
    /Users/corprew/demo/unirest-ruby/test/unirest_test.rb:129:in `block in <class:RequestsTest>'
    /Users/corprew/.rvm/gems/ruby-2.0.0-p247/gems/shoulda-context-1.2.1/lib/shoulda/context/context.rb:413:in `instance_exec'

Caching?

Is there a way to cache web request setting expiration manually?

Jruby Support

Any chance we can get jruby support here? The ruby 2.x dependency breaks it, along with a few ruby 2.x features. That stuff is coming in jruby, but its still got a while.

Upgrading to Rails 4.2.7 breaks funcitonality.

Using Rails 4.2.7 caused my connection to mashape that I use in my seed file to fail and generates the warning:

[warning] The response contained in an RestClient::Exception is now a RestClient::Response instead of a Net::HTTPResponse, please update your code

Downgrading to 4.2.6 fixes issue. Not sure it's an actual Unirest issue or a Rails issue, so posting just FYI.

How do I handle timeout?

I tried forcing a timeout and got a RuntimeError raised with the message "Request Timeout".

Is that it ? Do I have to test the message of a generic exception ? Shouldn't it raise something more particular like TimeoutError or anything like that ?

Thanks in advance.

Unirest headers not interpreted correctly

I'm trying to post JSON data but the host is interpreting the request as XML. I tested with httpbin.org, results below.

The post request:
Unirest.post("http://httpbin.org/post", headers:{ "Content-Type" => "application/json" }, parameters: { "a"=> "b"} )

The response:

{"args"=>{}, "data"=>"", "files"=>{}, "form"=>{}, "headers"=>{"Accept"=>"*/*; q=0.5, 
application/xml", "Accept-Encoding"=>"gzip, deflate", "Content-Length"=>"0", 
"Content-Type"=>"application/x-www-form-urlencoded", "Headers"=>
"{\"Content-Type\"=>\"application/json\"}", "Host"=>"httpbin.org", "Parameters"=>"{\"Inputs\"=>
{\"a\"=>\"b\"}}", "User-Agent"=>"unirest-ruby/1.0"}, "json"=>nil, 
"origin"=>"41.203.219.198", "url"=>"http://httpbin.org/post"}

The Headers key (uppercase h) contains the correct header values, while the headers key (lowercase h) contains different header values. The headers key is the one that's being accepted.

Upgrade gem version

There is no new version of the gem, so we get old dependencies like rest-client (~> 1.6.7).

Please upgrade to 1.1.3

Parameters property for body?

Parameters property should be called body when it is not a POJO or Query delimiter separated parameters like the other unirest libraries.

How to post json?

My service is not supporting parameters, just recieve json entity. So I wanna to post json entity to server, how can I do that?

thanks.

Gem: POST method needs "body" rather then "parameters" parameter

After being unsuccessful in doing a POST request as per the documentation I dug into the code in the current version of the gem on rubygems (unirest-1.0.8) and discovered that while the documentation states that the post method takes a "parameters" parameter with the POST body, the actual method is expecting a "body" parameter.

  def self.post(url, headers = {}, body = nil, &callback)
    return HttpClient.request(:post, url, headers, body, &callback)
  end

Token-based HTTP Authentication

Would you accept a pull request for http token authorization in unirest? It's handy in one of our projects and it seems like something that might be useful upstream (http header authorization tokens, not oauth.)

Bump and republish

Can you bump the version and republish to RubyGems so that the current version will use the rest-client 1.8 instead of 1.6?

BTW, rest-client 1.6 depends on an older version of mime-types, whereas rest-client 1.8 allows for newer versions of mime-types, which are supposed to consume less memory.

Thanks.

Issue with base64 encoding of Authorization header

Unirest encodes Authorization header data slightly differently than Net::HTTP. I actually hit this insidious bug while building an api wrapper to TangoCard Raas api. I kept getting "Request header field is missing ':' separator." and couldn't for the life of me figure it out. I spent 4 hours digging through source and manually crafting Net::HTTP requests.

Finally, I realized the Authorization header that Unirest creates has a newline in it, but those created by Net::HTTP, didn't.

In Unirest:

  "Basic " + Base64.encode64(user + ":" + password)

In Net::HTTP

  'Basic ' + ["#{account}:#{password}"].pack('m').delete("\r\n")

Not sure what should be done here...

Response body / parsing to a ruby Hash

Hi. When I pull the API data into a Ruby on Rails web app, I think it should be a Hash object, but for some reason, I'm unable to run any Hash methods on it.

Example for Mexico is below. Despite the square brackets, It doesn't seem to be an Array either. I tried running both Hash methods and Array methods on the parsed body, and simply got a Nil Class error: undefined method `[]' for nil:NilClass

Any idea how I might be able to resolve? I would like to get the parsed response body, and then run several Hash methods on it in my rails program.Thanks!

[{ "name"=>"Mexico", "capital"=>"Mexico City", "altSpellings"=>["MX", "Mexicanos", "United Mexican States", "Estados Unidos Mexicanos"], "relevance"=>"1.5", "region"=>"Americas", "subregion"=>"Central America", "translations"=>{"de"=>"Mexiko", "es"=>"México", "fr"=>"Mexique", "ja"=>"メキシコ", "it"=>"Messico"}, "population"=>121740000, "latlng"=>[23.0, -102.0], "demonym"=>"Mexican", "area"=>1964375.0, "gini"=>47.0, "timezones"=>["UTC−08:00", "UTC−07:00", "UTC−06:00"], "borders"=>["BLZ", "GTM", "USA"], "nativeName"=>"México", "callingCodes"=>["52"], "topLevelDomain"=>[".mx"], "alpha2Code"=>"MX", "alpha3Code"=>"MEX", "currencies"=>["MXN"], "languages"=>["es"] }]

Unirest not working, conflicts with addressable

Hi guys!

I'm trying to use Unirest but I get an error:

'raise_if_conflicts': Unable to activate unirest-1.1.2, because addressable-2.4.0 conflicts with addressable (~> 2.3.5) (Gem::ConflictError)

Looks like there's a conflict with the version of addressable. How can I fix this?

Webmock

Any chance for adding support for Unirest in Webmock?

Json deprecation warning on ruby 2.7.1

I am getting this deprecation warning caused by a dependence for an older version of json gem. Is it possible to upgrade the dependency?

bundle/ruby/2.7.0/gems/json-1.8.6/lib/json/common.rb:155: warning: Using the last argument as keyword parameters is deprecated

NoMethodError thrown when given an invalid domain name

On Ubuntu 1304/rvm/MRI 2.1, the following code results in a NoMethodError:

require 'unirest'
Unirest.get("http://foo.bar")

The internal SocketError should probably be raised up, or should mark the response as an error. I'm unsure of the intended behavior, otherwise I'd fork and fix.

URI.escape is obsolete

I'm using unirest-1.0.8 on ruby 2.7.0`

Calling a simple GET request the console shows me

http_request.rb:46: warning: URI.escape is obsolete

Some documentation related to the issue:

Unirest if only installable if ruby = 2.0

Hey !
This gemspec line seems to be problematic :

s.required_ruby_version = '~> 2.0'

I had to install ruby (2.0.0-p451) and using it instead of ruby 2.1.1. However, the official docs says that the requirement is Ruby >= 2.0

Can you check it ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.