5

Struggling a bit with faraday. I would like to know what I actually send to the server. I get the response body, but not access the request body. I found that there is a request.env method, but I can't get access to the body there somehow.

How would that work?

conn = Faraday.new(:url => 'http://sushi.com') do |faraday|
  faraday.request  :url_encoded             # form-encode POST params
  faraday.response :logger                  # log requests to STDOUT
  faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
end

data = conn.post do |req|
  req.url '/nigiri'
  req.headers['Content-Type'] = 'application/json'
  req.body = '{ "name": "Unagi" }'
end

# how do I get access to the request body here?

What I tried doing was this:

[4] pry(main)> request.env.request

=> #<struct Faraday::RequestOptions
 params_encoder=nil,
 proxy=nil,
 bind=nil,
 timeout=nil,
 open_timeout=nil,
 boundary=nil,
 oauth=nil>

But I have no access to the body. Any ideas?

Thanks!

Hendrik
  • 4,849
  • 7
  • 46
  • 51
  • I don't see a good way to do this either, the Faraday::Request object that gets created is ephemeral once the response comes back :\ – Anthony May 29 '16 at 14:09

1 Answers1

8

You could try implementing a middleware just for this purpose. Just to give you a quick idea on what you can do to achieve this (there might be an easier way but I don't really know, I suppose because you specify the request body there's no real need to capture this as you should already have this available).

require 'faraday'

class RequestBody < Faraday::Middleware
  def call(env)
    request_body = env.body

    @app.call(env).on_complete do |response|
      response[:request_body] = request_body
    end
  end
end

conn = Faraday.new(:url => 'http://sushi.com') do |faraday|
  faraday.use RequestBody
  faraday.adapter Faraday.default_adapter
end

data = conn.post do |req|
  req.url '/nigiri'
  req.headers['Content-Type'] = 'application/json'
  req.headers['foo'] = 'bar'
  req.body = '{ "name": "Unagi" }'
end

# 2.2.2 > data.env[:request_body]
#  => "{ \"name\": \"Unagi\" }"
# 2.2.2 > data.env.request_headers
#  => {"User-Agent"=>"Faraday v0.9.2", "Content-Type"=>"application/json", "foo"=>"bar"}
# 2.2.2 > data.body
#  => "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n<html><head>\n<title>301 Moved Permanently</title>\n</head><body>\n<h1>Moved Permanently</h1>\n<p>The document has moved <a href=\"http://www.sushi.com/index.php/nigiri\">here</a>.</p>\n<hr>\n<address>Apache/2.4.10 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4 PHP/5.4.32 Server at sushi.com Port 80</address>\n</body></html>\n"
Nabeel
  • 2,272
  • 1
  • 11
  • 14