Ruby: Receive JSON in Request Body
Join the DZone community and get the full member experience.
Join For FreeI’ve been building a little Sinatra app to play around with the Google Drive API and one thing I struggled with was processing JSON posted in the request body.
I came across a few posts which suggested that the request body would be available as params['data'] or request['data'] but after trying several ways of sending a POST request that doesn’t seem to be the case.
I eventually came across this StackOverflow post which shows how to do it:
require 'sinatra' require 'json' post '/somewhere/' do request.body.rewind request_payload = JSON.parse request.body.read p request_payload "win" end
I can then POST to that endpoint and see the JSON printed back on the console:
dummy.json
{"i": "am json"}
$ curl -H "Content-Type: application/json" -XPOST http://localhost:9393/somewhere/ -d @dummy.json
{"i"=>"am json"}
Of course if I’d just RTFM I could have found this out much more quickly!
Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments