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 or request 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!
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.