Routing

Edit this Page

In the context of web development, routing describes the process by which a web application receives a request from a browser and decides which code to run order to generate an appropriate response. This process lies at the heart of every web application.

How this works depends on the particular programming languages and libraries used, but the core idea is the same:

  1. The browser sends a request to our web application.
  2. Our application looks at the request data.
  3. Our application routes the request to the appropriate chunk of code.
  4. Our application calls that chunk of code to generate a response.
  5. Our application sends the response back to the browser.
  6. The browser renders the response.

Any routing system will need to express a few key ideas:

  1. How do we match against the parts of an incoming request?
  2. How do we specify which code to call for a match?
  3. How does the code-to-be-called specify the response?

In Sinatra

Keeping the above key ideas in mind, here's a specific example using Sinatra (a web framework for Ruby):

require "sinatra"  # Load the Sinatra web framework

# Set up a chunk of code to call when GET requests come to /hello
get("/hello") do
  # Generate an HTML response to send to the browser
  body("<p>Hello, world!</p>")
end

# Set up a chunk of code to call when POST requests come to /hello
post("/hello") do
  # Generate an HTML response to send to the browser
  body("<p>Oh, a POST request!</p>")
end

In the above application we're specifying two possible "routing matches" and the code to be run when a match occurs. The code-to-be-run is defined by the do ... end blocks. Remember, this is specific to Sinatra. Other frameworks will implement routing differently.

Let's answer the general questions from above using this example.

  1. How do we match against the various parts of an incoming request?

    We're matching against two parts of the request data:

    1. The request's type (i.e., GET, POST, DELETE, etc.)
    2. The request's path

    Given a URL like http://example.com/fancy/pants, the path is everything in the URL after the name of the server (/fancy/pants in this case).

    get("/hello") matches any GET request for a URL with the path /hello. post("/hello") matches any POST request for a URL with the path /hello.

  2. How do we specify which code to call for a match?

    We specify the code-to-be-called with a do ... end block. In the route

    get("/hello") do
      body("<p>Hello, world!</p>")
    end
    

    the code-to-be-called is everything after the do keyword and before the corresponding end keyword.

  3. How does the code-to-be-called specify a response?

    We specify a response by calling the body method and passing it a String containing the HTML we want the browser to render. Sinatra will generate the other parts of the request for us and send everything back to the requesting browser.