Make Requests

Making a request is very simple:

require "httpx"
puts HTTPX.get("https://google.com").to_s #=> "<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">..."

Performing a request will return an HTTPX::Response (except when there is an error) , which will allow you to perform a few more operations beyond getting the payload. For instance, this is how you’d check it’s status and headers:

require "httpx"
response = HTTPX.get("https://google.com")
puts response.status #=> 302
puts response.headers["location"] #=> "https://www.google.pt/?gfe_rd=cr&dcr=0&ei=v7prWubpNsPBXvDwocAD"

Many other request type methods are available:

require "httpx"
HTTPX.post("http://example.com", body: "blabla")
HTTPX.put("http://example.com")
HTTPX.patch("http://example.com", body: "blabla")
HTTPX.delete("http://example.com")
HTTPX.head("http://example.com")
# ...

Multiple Requests

Sending multiple requests is as simple as passing them. An array of responses will be returned:

require "httpx"

responses = HTTPX.get("https://www.google.pt/search?q=john", "https://www.google.pt/search?q=paul", "https://www.google.pt/search?q=george", "https://www.google.pt/search?q=ringo")

puts responses.map(&:to_s) #=> "<HTML>..."

# since v0.9, You can also pass different requests like this:

requests = [
  ["GET", "https://nghttp2.org/httpbin/get"],
  ["POST", "https://nghttp2.org/httpbin/post", { body: "bla" }]
]

responses = HTTPX.request(requests)

# Or, when a session object is available
session = HTTPX.plugin(:retries)

requests = [
  session.build_request("GET", "https://nghttp2.org/httpbin/get"),
  session.build_request("POST", "https://nghttp2.org/httpbin/post", { body: "bla" })
]

# IMPORTANT! pass the requests to the session which was used to build them! And use them only once!
responses = session.request(*requests)

:origin (since v0.14)

If you’re only going to query a single domain (i.e. if you are building an API SDK), you can set it using the :origin option, and then send requests using the relative paths only):

api_client = HTTPX.with(origin: "https://api.example.com")
api_client.get("/v1/pages/1")

:base_path (since v0.20)

You can also set a base path to be prepended to all relative URLs (quite useful for adding API version):

api_client_v1 = HTTPX.with(origin: "https://api.example.com", base_path: "/v1")
api_client_v1.get("/pages/1")

URI

You can also pass a URI object instead of the “string” uri:

uri = URI("https://www.google.pt/search?q=john")
HTTPX.get(uri)

IDN

Internationalized domain name are also supported:

HTTPX.get("http://bücher.ch")

Next: Pass Parameters