How to parse JSON request body in Sinatra just once and expose it to all routes? How to parse JSON request body in Sinatra just once and expose it to all routes? ruby ruby

How to parse JSON request body in Sinatra just once and expose it to all routes?


Use a sinatra before handler:

before do  request.body.rewind  @request_payload = JSON.parse request.body.readend

this will expose it to the current request handler. If you want it exposed to all handlers, put it in a superclass and extend that class in your handlers.


You can also use Rack Middleware to parse it. See https://github.com/rack/rack-contrib Just use Rack::PostBodyContentTypeParser when initializing your Sinatra class.


Like this working for sinatra 1.4.5

before do  if request.body.size > 0    request.body.rewind    @params = ActiveSupport::JSON.decode(request.body.read)  endend