Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I inspect the full URL generated by HTTParty?

I want to look at the full URL the HTTParty gem has constructed from my parameters, either before or after it is submitted, it doesn’t matter.

I would also be happy grabbing this from the response object, but I can’t see a way to do that either.

(Bit of background)

I’m building a wrapper for an API using the HTTParty gem. It’s broadly working, but occasionally I get an unexpected response from the remote site, and I want to dig into why – is it something I’ve sent incorrectly? If so, what? Have I somehow malformed the request? Looking at the raw URL would be good for troubleshooting but I can’t see how.

For example:

HTTParty.get('http://example.com/resource', query: { foo: 'bar' })

Presumably generates:

http://example.com/resource?foo=bar

But how can I check this?

In one instance I did this:

HTTParty.get('http://example.com/resource', query: { id_numbers: [1, 2, 3] }

But it didn’t work. Through experimenting I was able to produce this which worked:

HTTParty.get('http://example.com/resource', query: { id_numbers: [1, 2, 3].join(',') }

So clearly HTTParty’s default approach to forming the query string didn’t align with the API designers’ preferred format. That’s fine, but it was awkward to figure out exactly what was needed.

like image 577
Leo Avatar asked May 13 '15 16:05

Leo


2 Answers

You didn't pass the base URI in your example, so it wouldn't work.

Correcting that, you can get the entire URL like this:

res = HTTParty.get('http://example.com/resource', query: { foo: 'bar' })
res.request.last_uri.to_s
# => "http://example.com/resource?foo=bar" 

Using a class:

class Example
  include HTTParty
  base_uri 'example.com'

  def resource
    self.class.get("/resource", query: { foo: 'bar' })
  end
end

example = Example.new
res = example.resource
res.request.last_uri.to_s
# => "http://example.com/resource?foo=bar" 
like image 115
victorkt Avatar answered Nov 14 '22 11:11

victorkt


You can see all of the information of the requests HTTParty sends by first setting:

class Example
  include HTTParty
  debug_output STDOUT
end

Then it will print the request info, including URL, to the console.

like image 12
DiegoSalazar Avatar answered Nov 14 '22 10:11

DiegoSalazar