I am using Net::HTTP for CRUD request in Sinatra application. For a delete request I need to send JSON along with request:
uri = URI.parse('http://localhost:3000')
http = Net::HTTP.new(uri.host, uri.port)
path = '/resource/resource-id'
request = Net::HTTP::Delete.new(path)
request.basic_auth('username', 'password')
response = http.request(request)
The above code sends DELETE request just fine, but when I send JSON,
request = Net::HTTP::Delete.new(path, '{"ids": ["abc123"]}')
request.basic_auth('username', 'password')
response = http.request(request)
it throws:
'400 Invalid URI'
I have used HTTParty gem a lot and I know it serves this purpose, but I do not want to include a gem for just one API.
Any help/pointers are greatly appreciated.
Update As @kimball and @Zoker suggested, here is what I did (I am using ruby-2.0.0-p643 MRI):
request = Net::HTTP::Delete.new(path, {'Depth' => 'Infinity',
'Content-Type' =>'application/json'})
request.body = '{"ids":["abc123"]}'
request.basic_auth('username', 'password')
response = http.request(request)
it throws:
'400 Invalid URI'
Update 2 Again as suggested in comments:
require 'json'
request.body = {"ids" => ["abc123"]}.to_json
result is still the same.
response = http.request(request)
=> #<Net::HTTPBadRequest 400 Invalid URI readbody=true>
the Net::HTTP::Delete.new() method provide pass params in header
you can use like this:
the params in
Delete.new(path,params)
is a hash, not a string.more important, the hash value must be a
String
[UPDATE]
we can put a json string into request.body like this
or you can generate json string yourself