Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Net::HTTP::Get and JSON responses

Tags:

I'm trying to connect to an API and retrieve the json results with my rails app, however it doesn't seem to work.

Take for example:

@request = Net::HTTP::Get.new "http://example.com/?search=thing&format=json" 

When I try the url in my browser it works! and I get JSON data, however when I try that in Ruby the body is nil.

>> y @request --- !ruby/object:Net::HTTP::Get  body:  body_stream:  header:    accept:    - "*/*"   user-agent:    - Ruby method: GET path: http://example.com/?search=thing&format=json request_has_body: false response_has_body: true 

Any thoughts?

like image 614
JP Silvashy Avatar asked Sep 05 '10 18:09

JP Silvashy


People also ask

How do I get JSON data in Ruby on Rails?

One way to use rails to parse json in a scalable and effective manner is to create a class that parses the JSON response and manages the data from the json fields using the object. The problem with this approach is we need to maintain the class and have to be clear on which fields are included in the JSON.


2 Answers

I usually use open-uri

require 'open-uri' content = open("http://your_url.com").read 

`

like image 102
jordinl Avatar answered Oct 22 '22 04:10

jordinl


You need to actually send the request and retrieve a response object, like this:

response = Net::HTTP.get_response("example.com","/?search=thing&format=json") puts response.body //this must show the JSON contents 

Regards!

PS: While using ruby's HTTP lib, this page has some useful examples.

like image 40
Pablo Fernandez Avatar answered Oct 22 '22 06:10

Pablo Fernandez