3

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 = File.read("./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
    MultiJson.load(params[:payload])
  end
end

The spec fails because last_response.body is empty.

Am I missing something here?

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

Update

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
127.0.0.1 - - [06/Jan/2014 01:16:27] "POST /api/v1/verify_payload HTTP/1.1" 200 6 0.0220

Thanks

Sig
  • 5,476
  • 10
  • 49
  • 89
  • The post is supposed to be invoked by a third-party service. I don't plan to invoke it from UI. – Sig Jan 05 '14 at 13:51
  • did you have a look into the logs? – phoet Jan 05 '14 at 14:22
  • Do you succeed with a GET request (or another route of course) ? btw: http://programmers.stackexchange.com/questions/14293/ruby-sinatra-best-practices-for-project-structure read the comment dealing with Padrino. – jgburet Jan 05 '14 at 17:43
  • Yes, GET requests work fine. ```curl http://localhost:9292/api/v1/whatever``` returns correctly ```from get request```. – Sig Jan 05 '14 at 17:46

1 Answers1

10

Sinatra just doesn't parse this data, because they are not form parameters.

Form parameter would look like this

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

Instead of params you can just use request.body.read or use rack contrib.

rack-contrib

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

require 'rack'

require 'rack/contrib'

  1. 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, http://jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/

Sir l33tname
  • 4,026
  • 6
  • 38
  • 49