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.
March 19th, 2010 at 9:49 am
In latest pre 1.0 release, the last example maybe:
request.POST()
http://rack.rubyforge.org/doc/classes/Rack/Request.html#M000224
March 19th, 2010 at 9:56 am
From my reading of the code, .body and .POST() are different. .body gives you exactly the content of the request, while POST does various parsing.
In fact, it looks like Sinatra uses POST() internally to get the params[] object setup right. http://github.com/sinatra/sinatra/blob/master/lib/sinatra/base.rb#L41
March 27th, 2010 at 11:01 am
You right, Chris.
`request.body.read` is the recommended way to get the request payload.
I guess `request.POST` parse the payload according to request header `content-type`. Say if it is x-www-form-urlencoded, then POST() will return a hash.
March 28th, 2010 at 1:23 pm
Yeah, both useful, but slightly different.