Introduction 

In this article, we’ll present the foremost popular gems by providing a brief description and code snippets of creating an invitation to the Dad Jokes API. The gems are going to be provided within the order from the most downloaded one to the smallest amount. 

Ruby language

Setup

The requests

In comparing the foremost popular Ruby HTTP Clients, we’ll make a GET and a POST request.

When making a GET request to the Dad Jokes API, we’ll expect to ascertain such an output:

<code class="language-ruby" data-lang="ruby"> {
        :id=>"5wHexPC5hib", 
        :joke=>"I made a belt out of watches once... It was a waist of time.", 
        :status=>200
    }

We will make POST requests to JSONPlaceholder, which is an API testing tool. we’ll provide this placeholder and TokenAuthentication to line the Authorization header to a specified token

  • Multipart to convert an invitation body hash into a form request and UrlEncoded to convert it into a URL-encoded request body
  • Retry to automatically retry requests upon different failures
  • Instrumentation to instrument requests using different tools
  • Logger to log both the request and therefore the response body and headers
  • RaiseError to see the response HTTP code and to flag out the 4xx or 5xx code

This level of commitment to the developer, happiness is impressive and is reflected within the Open Source community. It comes as no surprise that Ruby Toolbox ranks this gem as the leader of all Ruby HTTP clients.

Rest-Client

Rest-Client

Rest-client is “a simple HTTP and REST client for Ruby, inspired by the Sinatra microframework sort of specifying actions: get, put, post, delete.” There really is extremely little complication as rest-client seems to be built to make RESTful API requests intuitive.

Here’s the GET request: require ‘rest-client’ 

<code class="language-ruby" data-lang="ruby">   require 'rest-client'
    require 'json'

    response = RestClient.get('https://icanhazdadjoke.com/', headers={ 'Accept' => 'application/json' })
    joke_object = JSON.parse(response.body)
    # =>  {"id"=>"szItcaFQnjb", "joke"=>"Why was the broom late for the meeting? He overswept.", "status"=>200}

    puts joke_object["joke"]
    # "Why was the broom late for the meeting? He overswept."

And the POST request:

require 'rest-client'
    require 'json'

    response = RestClient.post('https://jsonplaceholder.typicode.com/posts', :body => {:title=>"Why I love Hitchhiker's Guide to the Galaxy", :body=>"42", :userId=>42})

    puts JSON.parse(response.body, symbolize_names: true)
    # {"title"=>"Why I love Hitchhiker's Guide to the Galaxy", "body"=>"42", "userId"=>"42", "id"=>101}

This gem for several developers feels comfortable but there’s a wake-up call on the horizon: the gem features a very low commit activity over the past 3 years, and there has been no new release in over a year. It basically means there could be little or no support, or maybe that the gem is not any longer maintained. it’s especially problematic given the new recent releases of Ruby and Rails.

HTTParty

HTTParty

The HTTParty gem was created to ‘make HTTP fun’. Indeed, with its intuitive and easy syntax, the gem is particularly popular among Ruby newbies and within the side projects.

The following two lines are all we’d like to form a successful GET request:

<code class="language-ruby" data-lang="ruby">   require "HTTParty"
    require 'json'

    response = HTTParty.get('https://icanhazdadjoke.com/' , :headers => { 'Accept' => 'application/json' } )
    joke_object = JSON.parse(response.body)
    # {"id"=>"xXgyXvXgFlb", "joke"=>"Doctor you've got to help me, I'm addicted to Twitter. Doctor: I don't follow you.", "status"=>200} 

    puts joke_object["joke"]
    # "Doctor you've got to help me, I'm addicted to Twitter. Doctor: I don't follow you."

And a POST request:

require 'HTTParty'
   require 'json'

   response = HTTParty.post('https://jsonplaceholder.typicode.com/posts', :body => {:title=>"Why I love Hitchhiker's Guide to the Galaxy", :body=>"42", :userId=>42})

   puts JSON.parse(response.body, symbolize_names: true)
   # {:title=>"Why I love Hitchhiker's Guide to the Galaxy", :body=>"42", :userId=>"42", :id=>101}

Because of how seemingly simple its syntax is, HTTParty wont to be seen because of the HTTP Client. Up until a year ago GitLab used it for a variety of features but, as outlined during this issue, they decided against it as HTTParty is “is both slow and uses tons of resources’ ‘, including preposterous memory allocation.

HTTP.rb

HTTP.rb may be a reliable and pleasant gem for people that need an easy-to-use client library for creating requests from Ruby. consistent with the documentation:

It uses an easy method chaining system for building requests, almost like Python’s Requests. Under the hood, via Ruby FFI bindings, HTTP.rb uses the Node.js HTTP-parser, a quick HTTP parsing native extension. This library is not just yet one more wrapper around Net::HTTP. It implements the HTTP protocol natively and outsources the parsing to native extensions.

It supports features like persistent connections and fine-grained timeouts and prides itself in “the best performance of any Ruby HTTP library which implements the HTTP protocol in Ruby rather than C.”

Here’s the GET request:

<code class="language-ruby" data-lang="ruby">require "http"

http = HTTP.accept(:json)
response = http.get('https://icanhazdadjoke.com/')

joke_object = response.parse
# => {"id"=>"UnWS0wcF6Ed", "joke"=>"Every machine in the coin factory broke down all of a sudden without explanation. It just doesn’t make any cents.", "status"=>200}

puts joke_object["joke"]
# "Every machine in the coin factory broke down all of a sudden without explanation. It just doesn’t make any cents."

And the POST request:

require "http"
require 'json'

response = HTTP.post('https://jsonplaceholder.typicode.com/posts', :form => {:title=>"Why I love Hitchhiker's Guide to the Galaxy", :body=>"42", :userId=>42})

puts JSON.parse(response.body)["joke"]
# {"title"=>"Why I love Hitchhiker's Guide to the Galaxy", "body"=>"42", "userId"=>"42", "id"=>101}

But, that’s not all: HTTP.rb offers flexibility to switch your requests with ease, to handle exceptions with pleasure and even to convert the response into different data types. you furthermore may have timeouts, compression, and protracted connections at your disposal.

There is, however, a red flag: a bit like Rest-Client, HTTP.rb has not seen any new updates in over a year, and there’s a high volume of open issues. This might indicate potential poor maintenance, high vulnerability, and suboptimal support.

Net::HTTP

Now that we covered the HTTP Clients that are popular which bring joy, let’s offer a point of reference on the other side of the spectrum of the dev happiness. Net::HTTP is pervasive in some developer circles, which, honestly, comes as a surprise.

Ruby’s standard library is already equipped with an HTTP client: the net/HTTP gem. it’s perhaps the foremost common and therefore the most cursed solution to creating API requests. There’s plenty of criticism for this gem, which include the cluttered syntax, or its incontrovertible fact that oftentimes, it immediately retries making an invitation upon failure.

However, given its importance within the Ruby ecosystem, let’s have a glance at how we’d make the request to receive a joke to would relieve a number of the frustration:

<code class="language-ruby" data-lang="ruby">require 'net/http'
require 'uri'
require 'json'

uri = URI.parse('https://icanhazdadjoke.com/')
request = Net::HTTP::Get.new(uri)
request['Accept'] = 'application/json'

req_options = {
  use_ssl: uri.scheme == 'https',
}

response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
  http.request(request)
end

joke_object = JSON.parse(response.body)
# => {'id'=>'7wciy59MJe', 'joke'=>'What’s Forest Gump’s Facebook password? 1forest1', 'status'=>200} 

puts joke_object[:joke]
# 'What’s Forest Gump’s Facebook password? 1forest1'

And this is often how we’d create a replacement post about our favorite novel:

require 'net/http'
require 'uri'

uri = URI('https://jsonplaceholder.typicode.com/posts')
response = Net::HTTP.post_form(uri, {:title=>"Why I love Hitchhiker's Guide to the Galaxy", :body=>"42", :userId=>42})

puts JSON.parse(response.body)
# {"title"=>"Why I love Hitchhiker's Guide to the Galaxy", "body"=>"42", "userId"=>"42", "id"=>101}

This is definitely a long-winded thanks to make an invitation.

There seems to be no good reason to submit any developer to the present monster of a gem, especially that’s not not fast and has just disastrous memory allocation rates.

Conclusion

Now that we’ve provided a summary, code snippets, and metrics of all gems, also as Ruby community updates connected to them, we might wish to offer a fast suggestion: if you’re wondering which gem to use for your codebase or a passion side project, do accompany Faraday. it’s the simplest support, the most important community, it’s widely popular, shockingly-well maintained, fast and performant in terms of memory. It comes as no surprise that this opinion is additionally shared by the Ruby toolbox. Ruby as a language was created to form developers happy.

Was this post helpful?