1

Right now my API accepts a request such as ?a[]=x&a[]=y using:

params do
  requires :a, type: Array[String]
end

My client can only send the query parameter as ?a[0]=x&a[1]=y which Grape does not understand, resulting in 400 (Bad Request).

Is it not possible to both accept a[] and a[0] with Grape? The other option is to send a request to another server first, converting from a[0] to a[], send that request to Grape, get the response from Grape and send that to the client, which seems really unnecessary.

Filuren
  • 661
  • 2
  • 7
  • 19
  • What prevents your client to generate such URLs? – spickermann Dec 14 '15 at 06:57
  • I have not been able to find a way to change from indices to brackets using the library, so maybe it was easier to change Grape to be more flexible. I could construct the parameters myself of course but I thought libraries should handle that. Qs (https://github.com/hapijs/qs#stringifying) can handle that for example, specifying brackets or indices easily (I am not using Qs however). – Filuren Dec 14 '15 at 10:33

1 Answers1

3

It is more to do with Rack than Grape. It's how Rack parses query strings, take a look at

rack-1.6.4/lib/rack/utils.rb

def parse_nested_query(qs, d = nil)
  params = KeySpaceConstrainedParams.new

  (qs || '').split(d ? /[#{d}] */n : DEFAULT_SEP).each do |p|
    k, v = p.split('=', 2).map { |s| unescape(s) }

    normalize_params(params, k, v)
  end

  return params.to_params_hash
rescue ArgumentError => e
  raise InvalidParameterError, e.message
end

?a[0]=x&a[1]=y will produce a hash => {"a"=>{"0"=>"x", "1"=>"y"}}, which based on the params is invalid.

While a non-indiced version ?a[]=x&a[]=y produces an array {"a"=>["1", "2"]}

For some great information on that @see http://codefol.io/posts/How-Does-Rack-Parse-Query-Params-With-parse-nested-query

jtzero
  • 2,204
  • 2
  • 25
  • 44