Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: PUT Request with JSON body?

I need to create an HTTP PUT request using ruby.

The request has a JSON body

I was able to generate the JSON body using:

require 'rubygems'
require 'json'
jsonbody = JSON.generate["message"=>"test","user"=>"user1"]

I need to send this PUT request to the url:

require 'open-uri'
url = URI.parse('http://www.data.com?access_token=123')

Can someone please tell me how I can do this in Ruby?

like image 747
dpigera Avatar asked Jan 21 '11 18:01

dpigera


2 Answers

Using restclient (gem install rest-client) like this:

require 'rubygems'
require 'rest_client'
require 'json'

jdata = JSON.generate(["test"])
RestClient.put 'http://localhost:4567/users/123', jdata, {:content_type => :json}

against the following sinatra service:

require 'sinatra'
require 'json'

put '/users/:id' do |n|
  data = JSON.parse(request.body.read)
  "Got #{data} for user #{n}"
end

works on my computer.

like image 133
Lars Tackmann Avatar answered Oct 19 '22 01:10

Lars Tackmann


Easiest way is with Net::HTTP:

require 'net/http'
http = Net::HTTP.new('www.data.com')
response = http.request_put('/?access_token=123', jsonbody)
like image 4
Andy Lindeman Avatar answered Oct 19 '22 03:10

Andy Lindeman