rubyfaraday

How can i retrieve query params from get request


I'm kind of new to Ruby and I stuck with a fairly simple task. I would like to pass GET parameters to Faraday's request. Here is my request function

def request
  @request ||= Faraday.new do |conn|
  conn.url_prefix = BASE_URL
  conn.headers = @@headers
  conn.request :json
  conn.response :json, parser_options: { object_class: OpenStruct }
end

Then this request method is being called like so

params = {"date_to": "2021.07.07", "date_from": "2022.01.30"}
request.get(url, params).body

I've tried to retrieve params in the request method using conn.params = @request.params But that didn' work.


Solution

  • When you want to use params in the request method then you have to apss it to the method like this:

    def request(params)
      @request ||= Faraday.new do |conn|
        conn.url_prefix = BASE_URL
        conn.headers = @@headers
        conn.params = params
        conn.request :json
        conn.response :json, parser_options: { object_class: OpenStruct }
    end
    

    And then call the methods like this:

    params = { "date_to": "2021.07.07", "date_from": "2022.01.30" }
    request(params).get(url).body