· ruby

Ruby: Receive JSON in request body

I'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_payload = JSON.parse request.body.read

  p request_payload


I can then POST to that endpoint and see the JSON printed back on the console:


{"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!

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket