Share This Article
In this article, you will learn how to use HTTParty in Ruby to make HTTP requests from your Ruby apps.
Why Use HTTParty?
Gems like HTTParty & Faraday prove that making HTTP requests can be fun & easy in Ruby.
You can easily install HTTParty to your Gemfile:
gem 'httparty'
And then run bundle install
in your terminal to download the dependencies.
Making a Basic HTTP Request with HTTParty
The most basic request you can make with HTTParty is an HTTP GET request. You can do that with a single line of code:
HTTParty.get("www.example.com")
You can easily make other types of requests such as POST, PUT, & DELETE by using the post
, put
and delete
methods.
For example, to send a POST request that contains JSON data you can do:
data = { user: { name: "John", age: 21 } }
HTTParty.post("www.example.com", body: data.to_json, headers: { "Content-Type" => "application/json" })
If you want to use Basic Auth, you can do that with the basic_auth
option:
data = { user: { name: "John", age: 21 } }
HTTParty.post("www.example.com", basic_auth: {username: "jane", password: "doe"}, body: data.to_json, headers: { "Content-Type" => "application/json" })
In this case, the username is “jane” & the password is “doe”.
Parsing HTTP Response Data
By default, the HTTParty gem will parse the response body as JSON data, but you can also parse it as XML data using the xml
method.
HTTParty.get("www.example.com").xml
Error Handling
One of the advantages of using an HTTP client is the ability to easily handle errors.
For example, you can catch an HTTP error as an exception:
begin
HTTParty.get("www.example.com")
rescue HTTParty::Error => e
puts e
end
You can also rescue different types of errors separately by catching them as different types of exceptions:
begin
HTTParty.get("www.example.com")
rescue HTTParty::Error => e
puts e
rescue StandardError => e
puts e
end
This can be useful if you want to handle HTTP errors differently than other types of errors.
Using a Proxy
If you need to use a proxy, you can configure HTTParty to use a proxy by setting the http_proxy
, and https_proxy
environment variables.
ENV['http_proxy'] = "http://127.0.0.1:8888"
ENV['https_proxy'] = "http://127.0.0.1:8888"
HTTParty.get("www.example.com")
Using a Timeout
By default, HTTParty will timeout after 30 seconds, but you can change that by setting the default_timeout
value:
HTTParty.default_timeout = 10
HTTParty.get("www.example.com")
Keep in mind that you should always handle timeouts as exceptions.
Summary
HTTParty makes HTTP requests fun & easy in Ruby. In this article, you’ve learned how to use it for making different types of requests, parsing responses, error handling, & using a proxy.
You should also check out the HTTParty documentation for more information about what you can do with it.