Reputation: 3912
I have this curl call:
curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"name":"abc", "orgid":"12", "subject":"my subject"}' http://localhost:3000/mysinatraapp
post '/mysinatraapp' do
unless request.preferred_type.eql? 'text/html'
# This is not really params hash. It will be a string like "{\"name\"=>\"abc\", \"orgid\"=>\"12\", \"subject\"=>\"my subject\"}"
params = request.env["rack.input"].read
...
...
halt 400 if params.length == 0
end
# This does not work
p "hi #{params['name']}"
end
p "hi #{params['name']}"
fails because it's not a hash. How do I make it work?
My goal is to make posted json as params
hash. so that I can use params
as usual.
Upvotes: 5
Views: 9079
Reputation:
You are actually passing a Ruby Hash instead of a JSON object.
Update your curl command to look like this:
-d '{"name":"abc","orgid":"12","subject":"my subject"}'
Then in your Sinatra action do like this:
params = JSON.parse(request.env["rack.input"].read)
Make sure you require 'json'
Upvotes: 18