DEV Community

Fidel Leal
Fidel Leal

Posted on

Customizing Requests With The HTTP Gem

Many APIs require requests to be formatted according to specific requirements. Beyond authentication tokens, it is often necessary to include custom headers that provide additional information to an API. The HTTP gem in Ruby provides several methods that allow us to tailor our requests.

For instance, the authorization() method sets the header of the same name:

response = HTTP.authorization("Bearer #{YOUR_ACCESS_TOKEN_HERE}").get(...)
Enter fullscreen mode Exit fullscreen mode

To inform the server of the expected format for the response's content, we can set the Accept header using the method with the same name:

response = HTTP.accept("application/json").get("http://yoururl.com")
Enter fullscreen mode Exit fullscreen mode

Defining custom headers is also straightforward, thanks to the headers() method. For example, Notion requires version information to be sent along with requests to its API. It is possible to include that header as follows:

response = HTTP.headers("Notion-Version" => "2022-06-28").post("https://api.notion.com/v1/databases")
Enter fullscreen mode Exit fullscreen mode

We can even chain all these methods together in our request:

response = HTTP.authorization("Bearer #{YOUR_ACCESS_TOKEN_HERE}").accept("application/json").headers("Notion-Version" => "2022-06-28").post("https://api.notion.com/v1/databases")
Enter fullscreen mode Exit fullscreen mode

In order to maintain code organization and readability, we could choose to stick to a single method and just pass a hash to headers(), as opposed to chaining multiple methods:

my_headers = { "Authorization" => "Bearer YOUR_ACCESS_TOKEN",
               "Notion-Version" => "2022-06-28",
               "Accept" => "application/json",
               "Your-Custom-Header" => "custom-header-value"}

response = HTTP.headers(my_headers).post("https://api.notion.com/v1/databases")
Enter fullscreen mode Exit fullscreen mode

In summary, the HTTP gem offers great flexibility to customize our requests, accommodating the needs of various APIs and facilitating more effective communication with different web services.

Top comments (0)