Lesson Tuesday

Now that we've had the chance to build some server-side applications with Sinatra, let's walk through the request-response loop in more detail.

1. Generating a Request


To access a page on a website, including one made with Sinatra, the user either types in the site's URL, clicks a link, or submits a form. The client makes a request to the server that hosts the site. As we learned earlier in this section, this request follows strict formatting rules called HTTP, or Hypertext Transfer Protocol. Specifically, HTTP requests from the client include four elements that will be sent to the server:

  • Method
  • Path
  • Headers
  • Body

HTTP Methods

HTTP methods, also known as verbs, indicate the type of action the client is requesting the server to complete. The most common HTTP methods are GET and POST.

GET Requests

Requests with GET methods retrieve resources from the server. For example, when we navigate to the LearnHowToProgram.com Courses page the client requests the resource at the URL https://www.learnhowtoprogram.com/courses. The server locates the content corresponding to the /courses URL path and sends it back to the client in a response. Our client essentially went out and got the necessary resources to render a page.

POST Requests

Unlike GET requests, POST requests actually aim to change something on the website's server. This includes adding, updating, or deleting albums.

For instance, when we like a friend's photo on social media, our client is sending a POST request because we're changing something on that site's server. We're both increasing the total number of likes recorded on that photo and adding our username to the list of those that like the picture.

In a previous lesson, we added this attribute to our form to create an album:

method="post"

We did this because we wanted to add an Album.

Path

In addition to an HTTP method, the client's request to the server also includes a path. The path identifies the web resource that should be retrieved (GET) or acted on (POST). In the example https://www.learnhowtoprogram.com/courses the resource /courses is known as the path.

If we were visiting the create form for new albums in our record store application, /albums/new is the path.

Headers

Headers are also part of the request message protocol. They provide the server with more information about the client, the server and the request. Here are some examples of header fields included in a request message:

  • Host: This is the host or domain name of the server. Examples include www.learnhowtoprogram.com and localhost:4567.
  • User-agent: This is the software acting on behalf of the user to make the request. In our example, this would be our browser, whether it's Chrome, Firefox, or something else.
  • Accept-language: This includes the human languages that are acceptable for the response.

There's no need to worry about headers too much yet. But for a list of all available request headers, check out the HTTP Headers Wikipedia article.

Body

HTTP Requests also include a body. The body contains any data (beyond the URL and headers) that must be transmitted to the server.

For example, when a user submits the new album form in our record store, the resulting POST request needs to include the specific information they typed in the form so the server can store this information as a new Album and later print it to our list of albums. This data is delivered to the server in the body of the request.

Viewing Requests

Remember, we can view HTTP requests and responses right in Chrome's developer tools:

  • Launch the record store application.
  • Visit the app at localhost:4567 and open developer tools (Command + Option + J on Mac or Ctrl + Shift + I on PC).
  • Select the Network tab (fourth from the left) on the top toolbar of the developer tool pane.
  • The second-from-top toolbar contains a checkbox titled Preserve log. Select this box.
  • Keeping this Network area open, hit the Add a new album link on our site's homepage. We should see a new request logged in the developer's tools. We can click this request to see details, including its URL, the GET HTTP request method it used, its headers, and more:

Using the DevTools _Network_ tab to inspect an HTTP GET request

  • Then we can fill out and submit our form to see yet another request. This time we see it's a POST request. If we scroll down, we can view its response headers and form data included in the request body:

Using the DevTools _Network_ tab to inspect an HTTP POST request

2. Routing in app.rb


After the client sends a request, the server receives it. The HTTP method and path are matched to a route in app.rb.

Our application server can identify what resource should be retrieved and sent back in its response by matching this path to the route in our controller that has the same path specified in the route decorator. It then executes that route's code.

3. Returning a Response


After the client creates and sends a request and our server matches the path in this request to the correct route, our server then returns an HTTP Response back to the client. Like our requests, this response is also formatted following special HTTP protocol. It consists of three primary elements:

  • Status
  • Headers
  • Body

Status

The first line of a response message is a status code and reason phrase. (An example is 200 OK, which is shown in the picture above.) The HTTP status code is a three-digit number that indicates how the request was processed (or not). Each is accompanied by a brief, human-readable description.

Below is a list of the five status code classes determined by the first digit of the code, and their most common codes. You don't have to memorize these; simply get an idea of what's out there, and refer back as necessary. (And, to see a complete list, visit HTTP Status Codes.)

  1. Informational: Status codes beginning with 1 indicate the request was received. This class of code is rarely used.
  2. Success: Status codes beginning with 2 indicate the request was received and handled successfully. These are very common. For example:
    • 200: OK
    • 201: Created
  3. Redirection: Status codes beginning with 3 indicate that additional action is required to complete processing the request. For example:
    • 301: Moved permanently
    • 302: Moved temporarily
  4. Client Errors: Status codes beginning with 4 indicate that something was wrong about the request. Some of the most common include:
    • 400: Bad Request (the request used invalid syntax)
    • 401: Unauthorized (you have to log in)
    • 403: Forbidden (you're logged in, but not allowed to make this request)
    • 404: Not Found
    • 422: Unprocessable (the request had valid syntax but the instructions it contained were invalid)
  5. Server Errors: Status codes beginning with 5 indicate that something went wrong on the server side, such as a bug in the code or a server that went down. For example:
    • 500: Internal Server Error (usually a bug in the server code)
    • 502: Bad Gateway (the server sent the request to another server and got an invalid response)
    • 503: Service Unavailable (the server is overloaded or down for maintenance)

Headers

Like request headers, response headers include additional protocol providing more details about the HTTP response. Some examples of response header fields include:

  • Server: The name of the server where the response is coming from.
  • Content-Language: The human language(s) of the content.
  • Content-Length: How long the response body is in 8-bit bytes.

For a list of all possible response headers, see here.

Body

The response body includes all of the content for the resource requested. It's often referred to as the payload. When we issue a GET request for the /albums/new path of our record store, we expect the body to include an HTML document with the form we created to make new Albums.

The last line of code in a route indicates the resource that should be returned in the body of the response. In the case of our application, the resource is a view.

4. Rendering the Page


When the browser receives the response from the server, it then renders the HTML into a viewable format for the user. The whole process begins again as the user actions trigger additional requests for the server to manage.

Lesson 29 of 37
Last updated August 7, 2022