Ruby Faraday - includes the same parameter several times

I am working against an API that forces me to send the same parameter name several times to cascade different filtering criteria. So the GET api example looks like this:

GET http://api.site.com/search?a=b1&a=b2&a=b3&a=c2

I use Faraday for my REST adapter, which takes its URL parameters as a hash (therefore - it has unique keys). This means that I cannot do something like this:

response = Faraday.new({
  url: 'http://api.site.com/search'
  params: { a: 'b1', a: 'b2', a: 'b3', a: 'c2' } # => nay
}).get

I tried to crack the URL just before sending the request:

connection = Faraday.new(url: 'http://api.site.com/search')
url        = connection.url_prefix.to_s
full_url   = "#{ url }?a=b1&a=b2&a=b3&a=c2"
response   = connection.get( full_url )

What didn't work - when I debug the answer, I see that the actual URL sent to the API server is:

GET http://api.site.com/search?a[]=b1&a[]=b2&a[]=b3&a[]=c2

I have no way to change the API. Is there any way to continue working with Faraday and solve it in an elegant way? thank.

+5
source share
3

, - . .

:params => {:color => ['red', 'blue']}

color=red&color=blue
+9

, 0.9.x

module Faraday
  module Utils
    def build_nested_query(value, prefix = nil)
      case value
      when Array
        value.map { |v| build_nested_query(v, "#{prefix}") }.join("&")
      when Hash
        value.map { |k, v|
          build_nested_query(v, prefix ? "#{prefix}%5B#{escape(k)}%5D" : escape(k))
        }.join("&")
      when NilClass
        prefix
      else
        raise ArgumentError, "value must be a Hash" if prefix.nil?
        "#{prefix}=#{escape(value)}"
      end
    end
  end
end
+2

I think that you incorrectly call Faraday. First you need to define a connection (without parameters), and then you call the HTTP method on that connection.

Something like that:

require 'faraday'

client = Faraday::Connection.new :url => "http://api.twitter.com" do |builder|
    builder.response :logger
    # some middleware that helps to process a request/response comes here
end

client.get "search", { a: 1, b:2 }

This will create you this query:

I, [2013-02-05T15:15:40.665955 #57012]  INFO -- : get http://api.twitter.com/search?a=1&b=2
0
source

All Articles