Skip to content
Advertisements

Taghttp

Adding Query Params to a URL in Ruby with HTTP

The clearest example was in a StackOverflow post

require 'uri'

def add_param(url, param_name, param_value)
 uri = URI(url)
 params = URI.decode_www_form(uri.query || "") << [param_name, param_value]
 uri.query = URI.encode_www_form(params)
 uri.to_s
end

You can pass a map of params key & values and get expected URL.

Another example

 # prepare params.
 params = { 'id' => '12' }

 path = 'http://localhost/'
 uri = URI(path)

 uri.query = URI.encode_www_form(params)

Output

http://localhost?id=12

Reference

A Resilient Web API Client in Ruby

Ruby HTTP client is not sophisticated enough to handle errors gracefully. I came across a well-designed client for a web service at [AppSignal].
(https://blog.appsignal.com/2018/05/16/ensure-retry-and-reraise-exceptions-in-ruby.html)

The code for the client is as following:

The code has the following logic:

  1. Try to establish a connection with the server.
  2. The request has a timeout and connection refused exceptions.
  3. If retries fail, code raise the last seen exception.
  4. Each retry has increased timeout.

Written with StackEdit.

%d bloggers like this: