Last Updated: February 25, 2016
·
9.324K
· mcansky

Sinatra and the JSON data

To mock an API I don't have control over I wrote a simple Sinatra app. I did so using rspec too to do things properly.

In specs there is an easy way to send post requests :

# [ ... ]
it "should work" do
  post '/action,
    foo_hash,
    headers
  last_response.should be_ok
end

In the sinatra app you can catch it :

post '/action' do
   logger.info params.inspect
end

Ok this works great. But foo_hash will be sent as simple params, translated properly into the needed strings. If you want to send data as JSON (as can be done with curl -d) here is what you need in the spec :

require 'json' # at the top of the file
# [ ... ]

it "should work" do
  post '/action,
    foo_hash.to_json,
    headers
  last_response.should be_ok
end

And in the routes :

require 'json'

post '/action' do
   logger.info JSON.parse(request.body.read.to_s)
end

And if you want you can then use a filter to do that for all actions :

before do
  @req_data = JSON.parse(request.body.read.to_s)
end

post '/action' do
   logger.info @req_data
end

And your data will be available using @req_data.

Conclusion

One could expect that behaviour from sinatra yet if you don't know it might be surprising. So here is one way to handle that json data properly.

Suggestions ?

1 Response
Add your response

Quite good, it's solved some of my problems.

over 1 year ago ·