rubynet-http

Passing array of id's as query parameter of net/http


I want to do a GET request like that using the standard Ruby client net/http:

stores/?ids=2,24,13

I'm trying to do it this way, where store_ids is an array of ids, but it is not working. If I pass a single id as a param for ids, the response is correct.

def get_stores_info
  uri = URI(BASE_URL)
  params = { ids: store_ids, offset: DEFAULT_OFFSET, limit: DEFAULT_LIMIT }
  uri.query = URI.encode_www_form(params)
  response = Net::HTTP.get_response(uri).body
  result = JSON.parse response
end

Solution

  • You can transform store_ids to string:

    store_ids = [2,24,13]
    params = { ids: store_ids.join(','), offset: 0, limit: 25 }
    
    # these are to see that it works.
    encoded = URI.encode_www_form(params) # => "ids=%5B2%2C+24%2C+13%5D&offset=0&limit=25"
    CGI.unescape(encoded) # => ids=2,24,13&offset=0&limit=25
    

    Here's a Replit.