Ruby send JSON request

Andy picture Andy · Jan 8, 2010 · Viewed 117.4k times · Source

How do I send a JSON request in ruby? I have a JSON object but I dont think I can just do .send. Do I have to have javascript send the form?

Or can I use the net/http class in ruby?

With header - content type = json and body the json object?

Answer

CarelZA picture CarelZA · Jan 21, 2014
uri = URI('https://myapp.com/api/v1/resource')
req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json')
req.body = {param1: 'some value', param2: 'some other value'}.to_json
res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end