TLDR
Use HTTParty if you can, else Net::HTTP does work, even if it gets clunky.
Introduction
Almost everyone needs to make HTTP requests. Ruby provides us a working(if non-ergonomic for HTTPS) way to do this in the standard library or third party gems like HTTParty.
The Net::HTTP package
The Net::HTTP package exists in the standard library and is thus a good option if you don’t want to add third party libraries. It has a few good(if sometimes long) ways to create a http request. Let’s try to understand them by working through an example an example.
Example GET request
Let’s keep our goal simple, we want to make a get request to google.com. Net::HTTP lets us do that in a very simple manner
Simple HTTP request
1
2
3
4
5
6
7
8
9
require "net/http"
response = Net::HTTP.get("www.google.com", "/")
# or
# response is of type Net::HTTPOK if request succeeds
response = Net::HTTP.get_response("www.google.com", "/")
response.body # contains the actual content of the response
But, there’s a catch, it won’t do https requests by default. To use https, we have to do something like the following
Simple HTTPS request
1
2
3
4
5
6
7
8
9
10
11
requre "net/http"
uri = URI("https://www.google.com")
request = Net::HTTP::Get.new(uri.request_uri)
# Fun side note, both requestor and requester seem to be proper English
requester = Net::HTTP.new(uri.host, uri.port)
requester.use_ssl = true # Can't use it as an optional method argument when initialising requester
# Same as the above example, it is an instance of Net::HTTPOK if it succeeds
response = requester.request(request)
You can see the dramatic increase in code size just for a simple https
request, which is almost always what you have to do instead of the insecure http
version.
Let’s add headers
Once we have the basic structure, everything else is just adding more values to the request
object. e.g. if we need to use a header.
1
2
3
#... create `request` object
request["header-key"] = "header-value"
#...
Let’s add basic auth
Similar to adding headers, we can add basic auth to the request
object.
1
2
3
#... create `request` object
request.basic_auth user, pass
#...
Net::HTTP conclusion
HTTPS has become almost essential nowadays and the standard approach is too long. It is very verbose and lacks simple convenience functions which are what differentiate ruby. Also, it does not follow redirects and you’ll have to manually write a loop to handle it.
Yet, it is very easy and no need for third party libraries is a win in my book.
Bonus: HTTParty
Now that you’ve tasted the long way, let make the same request in HTTParty.
1
gem install httparty
1
2
3
4
5
6
7
require 'httparty'
response = HTTParty.get(
"https://google.com",
headers: {"header-key" => "header-value"},
basic_auth: {username: user, password: pass}
)
This is so much simpler. So, just use this if you can. Otherwise the standard library’s way is just somewhat more tedious and that can easily be wrapped inside a class of our own.
Cheers and see you next time.