More on Routing

When creating routes within our Sinatra application, we’re mapping requests. Until now we’ve looked at ‘GET’ Requests. These are the most common way that information is requested from a webserver and the type of request you’ll most often used. But, depending on what we’re doing we may use other kinds of requests.

What just happened?

Sinatra intercepts the HTTP requests coming to it and it allows you to map them to custom actions in Ruby code that do things and send a response. This is illustrated in the image below.

Routes

The way we map onto them is by defining an action in our Ruby code file like so:

Action

To allow this to work, we need to include four bits of information about how the HTTP request is mapped onto an action:

  • The type of HTTP request. This is normally GET.
  • The endpoint that we want to map our code to. This is the bit in the browser after the domain (something.com). The default route is /. This is handled in the case where we just type the server URL into the browser and don’t add anything onto the path.
  • The action itself. This begins at the do and completes at the end and is represented by the code we write; and
  • The response. Normally the last line of the block is what’s returned back to the client as part of the request

HTTP methods

There are technically 8 different HTTP methods:

  • GET
  • POST
  • PUT
  • DELETE
  • OPTIONS
  • HEAD
  • TRACE
  • CONNECT

For routing, you’ll only ever really need to deal with the first four.

get '/something' do
  .. show something ..
end

post '/something' do
  .. create something ..
end

put '/something' do
  .. replace something ..
end

delete '/something' do
  .. annihilate something ..
end

Notice that all four have the same ‘endpoint’ or name for the route, but they can each do different things. This gets really useful later. More on that when we get to databases and interacting with webhooks from other services!

×

Subscribe

The latest tutorials sent straight to your inbox.