In Sinatra, routing is how your app responds to requests, by the path of the request (e.g. /welcome
) and by the HTTP
verb used (e.g. GET
or POST
). The way a request is written is as follows:
<http-verb> <path> do
<code block to execute when this route is requested>
end
Here is an example that responds to GET
requests to the path /hello
by returning a page that says "Hi, whats up":
get "/hello" do
return "Hi, whats up"
end
Sinatra only responds to routes that you define. If you do not define a route, Sinatra returns a 404 Page Not Found
error page.
Sinatra responds to routes in the order they are defined. If you have several routes that can match a given request (see "Regexp based path matching"), the first route that fits the request is returned.
NOTE: Sinatra treats routes with and without trailing forward-slash (/
) as 2 different and distinct routes. That is, get '/hello'
and get '/hello/'
by default match different blocks of code. If you want to ignore the trailing forward-slash and treat both routes as the same, you can add ?
after the forward-slash to make it optional, like so: get '/hello/?'
. This uses Sinatra's ability to use regular expressions for route matching (more on this below).