JSON POST-Request with the Ruby HTTPX gem
Many of the most popular HTTP client libraries for Ruby are quite outdated. Some of them have been last released almost four years ago. Some of them no longer work with Let’s Encrypt certificates. And almost all of them are heavily depended on by other gems.
The HTTPX tries to keep the best parts of the older gems, while supporting a wide range of protocols, proxies, compressions and authentication methods.
The library is not very widely used, and it is sometimes difficult to find usage examples for specific use cases, especially on how to send JSON requests.
First things first, in order to send a JSON GET request:
response = HTTPX.get("https://api.github.com/users")
data = response.json
data #=> { "login" => "octocat", "id" => 1, "node_id" => "MDQ6VXNlcjE=", ... }
As you can notice, calling #json
on the response automatically parses the response
if the content type of the response was application/json
. HTTPX throws an exception
otherwise.
To send a POST request with a JSON payload:
response = HTTPX.post("https://api.github.com/orgs/octocat/repos", json: { name: 'My new repo' })
data = response.json
data #=> { "name" => "My new repo", ... }
If a request fails for an unknow reason, HTTPX has a debug mode. To enable it, set the
debug level to either 1
or 2
:
HTTPX.with(debug_level: 2, debug: $stderr).get("https://api.github.com/users")
This will print very detailed debug messages, down to the ethernet frame level.