I am writing an API and it receives a JSON payload as the request body.
To get at it currently, I am doing something like this:
post \'/doSomething\'
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.
before do
request.body.rewind
@request_payload = JSON.parse(request.body.read, symbolize_names: true)
end
So you can also symbolize_names while parsing JSON request body, this will give you access to your nested params like this @request_payload[:user]
You can parse your JSON post body as a Hash
with Rack::PostBodyContentTypeParser
from https://github.com/rack/rack-contrib:
require 'rack/contrib/post_body_content_type_parser'
class Api < Sinatra::Application
use Rack::PostBodyContentTypeParser
...
end
You can even pass a custom block to Rack::PostBodyContentTypeParser
to parse the JSON as symbols instead of strings:
a_proc = proc { |body| JSON.parse(body, symbolize_names: true, create_additions: false) }
use Rack::PostBodyContentTypeParser, &a_proc
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)
end
end
Use a sinatra before handler:
before do
request.body.rewind
@request_payload = JSON.parse request.body.read
end
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.