Making HTTP Requests in Ruby with the httpx Gem

Feb 5, 2024 ยท 2 min read

The httpx gem provides a simple and flexible way to make HTTP requests in Ruby. It wraps the standard library's Net::HTTP with a cleaner API and useful features like persistent connections and timeouts.

Getting Started

To install httpx:

gem install httpx

Then require it in your code:

require 'httpx'

Making a basic GET request is simple:

response = HTTPX.get("https://example.com")

The response contains the status code, headers, and body:

puts response.code # 200
puts response.headers["Content-Type"] # "text/html"
puts response.body # "<html>...</html>"

Configuring Requests

You can customize requests in a variety of ways:

response = HTTPX.get("https://example.com", 
  params: {key: "value"}, # query string parameters
  headers: {Authorization: "Bearer xyz"} # custom headers
) 

Set timeouts, follow redirects, attach cookies, and more.

Handling Responses

httpx makes it easy to handle common status codes:

begin
  response = HTTPX.get("https://example.com/does_not_exist") 
rescue HTTPX::NotFound
  puts "Whoops, resource not found!"
end

It raises custom errors for 400, 500, and other status codes.

Persistent Connections

Creating a client reuse TCP connections:

client = HTTPX::Client.new
client.get("https://example.com/1")
client.get("https://example.com/2") # reuses connection

This avoids overhead of creating new connections.

httpx wraps and simplifies Ruby's HTTP client with a clean interface, while providing useful functionality like persistent connections. It's great for APIs, web scraping, and tasks involving HTTP requests.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!