The cycle of HTTP requests

Erin Cola
2 min readJan 22, 2021

One major thing I’ve learned while diving into my Sinatra project is the cycle of HTTP requests. It is one of the most important concepts to understand in building web applications. First things first, it is important to know that HTTP is a stateless request. This means that no request can ever find out about a previous request made. Every single request happens in isolation of another. This means that it is impossible for one controller action to pass data to another controller action. It helps to keep the memory clear and running smoothly.

Now the request cycle itself is another very important concept. The request happens in 8 steps. These 8 steps happen in a tenth of a second. All of this information traveling from a user, to a server, and back again at the speed of light. First, the user will make an HTTP request by submitting a URL into their browser. Sinatra then grabs that information and routes it to the correct action. That action then asks the models, which are responsible for holding your databases, for objects. The model then grabs that data. Your database will then respond to such request. The model will then send the objects to the action. That action will then send the object to your views file for rendering. The view will then respond with HTML. Finally, the controller will send back said HTML in an HTTP response and pop up on a users browser. Pretty cool!

This is now where another important concept will come into play. The rendering vs redirect commands. By rendering, you are basically telling Sinatra which view to show a user, without losing the access to the instance variables in that controller action. You will use this when you’re not changing any data. However on the contrary to that is the redirect command. Redirect is used when data has been changed. The redirect method will tell your browser to send a request to another URL. Since HTTP requests are stateless, it is a completely different request and will therefore not have access to any variables defined in your controller. Basically, if an instance variable is required to make the new request then one would use the render method, in this case erb (embedded ruby) to show the page. Otherwise, if an instance variable is not needed to make the new request, one would use the redirect method to make a new request. In summary, if you’re going to need anything from your controller in the view, then render, and if not, redirect.

All of these concepts are extremely important to understand. I hope this has helped anyone confused about the entire cycle!

--

--

Erin Cola
0 Followers

My name is Erin and I am super new to the tech world, and also so excited and eager to become a part of it. :)