0

I am trying to setup a POST request to a rest api using ruby. What I want to do is to output the raw HTTP request without actually sending the request. I have looked at HTTParty and Net:HTTP, but it seems the only way to output the request is only once you send the request. So basically I want a convenient way for creating an HTTP request string without actually having to send it.

Charles
  • 50,943
  • 13
  • 104
  • 142
Wahaj Ali
  • 4,093
  • 3
  • 23
  • 35
  • if you are trying to make this for testing 3rd party service... and you want to mock this request (not sending the actual request to the 3rd party service but generate a response for this request locally) ... then i urge you to check https://github.com/bblimke/webmock – a14m Mar 08 '14 at 23:16

2 Answers2

0

The HTTParty.get and similar methods methods are helper functions that wraps a lot of the internal complexity; you should just peek inside the method to find that HTTParty.get to find that inside it it just makes a call to perform_request:

def get(path, options={}, &block)
  perform_request Net::HTTP::Get, path, options, &block
end

and peeking into perform_request, we get that it just constructs a Request object and call perform on it:

def perform_request(http_method, path, options, &block) #:nodoc:
  options = default_options.merge(options)
  process_headers(options)
  process_cookies(options)
  Request.new(http_method, path, options).perform(&block)
end

You should take a look into the Request class.

Lie Ryan
  • 62,238
  • 13
  • 100
  • 144
  • Thanks for the answer. Already tried that, but internally in the Request class the method to create the request is private (setup_raw_request). I could open the class and change somethings, but that wouldn't be the ideal elegant solution I am looking for. – Wahaj Ali Mar 09 '14 at 07:54
0

Take a look at Typhoeus

request = Typhoeus::Request.new(
  "www.example.com",
  method: :post,
  body: "this is a request body",
  params: { field1: "a field" },
  headers: { Accept: "text/html" }
)

It allows you to create the request and then you can run it or not with

 request.run
Rafa Paez
  • 4,820
  • 18
  • 35