Getting data into a Sinatra Application
There are several ways of getting parameters and data into your Sinatra application.
1) URL Options
get '/post/:id' do
post_id = params[:id]
end
# Several options, period gets interpreted as a separator between the two.
get '/author/:id.:format' do
author_id = params[:id]
format = params[:format]
end
# Several options, separated by '/'
get '/author/:author_id/comments/:comment_id' do
author_id = params[:author_id]
comment_id = params[:comment_id]
end
2) URL Parameters - the classic ?foo=bar&baz=quux
# this will get the post id out of /author?id=2
get '/author' do
author_id = params[:id]
end
# Works the same way for the POST method (and DELETE and PUT of course)
post '/author' do
author_id = params[:id]
end
3) Raw Posted Data - if the POSTed content is in the “application/x-www-form-urlencoded” format, it will get parsed as above, with the params[:id] method of getting the data. But occasionally, you want the whole chunk of raw data. This is useful for images, or big chunks of xml.
post '/data' do
raw = request.env["rack.input"].read
end
June 15th, 2008 at 7:45 pm
A slightly shorter version of the last example: raw = request.body.string
June 15th, 2008 at 8:41 pm
Your right, you should be able to skip the env call.
To keep it the same as my original example, it would be: request.body.read.