macsig macsig - 1 year ago 130
JSON Question

reading parameters on Sinatra post

I'm working on my first Sinatra app and I have an hard time getting parameters from a post request.

I'm using MiniTest::Spec and my spec looks like

payload ="./spec/support/fixtures/payload.json")
post "/api/v1/verify_payload", { payload: payload }, { "CONTENT_TYPE" => "application/json" }
last_response.body.must_eql payload

And this is my route

namespace '/api/v1' do
post '/verify_payload' do

The spec fails because
is empty.

Am I missing something here?

I also tried to return the entire
but also in that case it returned an empty string.


curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' http://localhost:9292/api/v1/verify_payload

does not return anything and no error on the server log

[2014-01-06 01:16:25] INFO WEBrick::HTTPServer#start: pid=10449 port=9292 - - [06/Jan/2014 01:16:27] "POST /api/v1/verify_payload HTTP/1.1" 200 6 0.0220


Answer Source

Sinatra just don't parse this data, because they are no form parameters.

Form parameter would look like this

curl -X POST 127.1:4567/ -d "foo=bar"

Instead of params you can just use or use rack contrib.


  1. Install it with gem install rack-contrib
  2. require it

    require 'rack'

    require 'rack/contrib'

  3. load it use Rack::PostBodyContentTypeParser

with this you can use params as normal for json post data. Something like this:

curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' 127.1:4567/

source for this: Sinatra controller params method coming in empty on JSON post request,

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download