rubynet-http

Ruby URI: build URI with "param[]=value" for array params


I'm trying to query an API (lichess API). And I can't get the params to be correctly taken into account, because URI formats the URL not in the expected format for array params.

The expected format is this one: curl https://explorer.lichess.ovh/lichess?ratings[]=2200&ratings[]=2500. So the ratings params is an Array of values, and the url should be using ratings[]=value.

I'm currently generating my URI like this, as per the doc:

base = "https://explorer.lichess.ovh/master"
params = {
  ratings: [1600, 1800]
}

uri = URI(base)
uri.query = URI.encode_www_form(params)

But this generate the URL like this: https://explorer.lichess.ovh/master?ratings=1600&ratings=1800... which is not the expected format, and is not understood by Lichess API.

Does Ruby provide any built-in way to generate the params in the expected format, or will I need to build the URL manually (which feels like revinventing the wheel)?


Solution

  • Rails/ActiveSupport has a to_query method which will do what you want.

    2.1.5 :010 > params.to_query
     => "ratings%5B%5D=1600&ratings%5B%5D=1800" 
    

    Also, have a look at this comment which explains why URI.encode_www_form doesn't return square brackets.