DEV Community

Cover image for 49 Days of Ruby: Day 34 - Ruby and HTTP
Ben Greenberg
Ben Greenberg

Posted on

49 Days of Ruby: Day 34 - Ruby and HTTP

Welcome to day 34 of the 49 Days of Ruby! 🎉

Today we are going to talk about HTTP and how you can build requests in Ruby.

First, what is HTTP?

HTTP stands for Hypertext Transfer Protocol. It is a protocol, or a set of conventions, that allows for the fetching of resources. Those resources most notably include HTML documents. HTML is the foundational language of a webpage, and HTTP is the protocol that lets you get it off the Internet.

You are viewing the DEV website right on using HTTP, and this blog post was put together using HTML!

There are other ways to make HTTP requests, though, then just with your web browser. You can do so in your Ruby code!

Making Ruby HTTP Requests

The library we will use and is standard for HTTP requests in Ruby, is net/http. You can find the documentation for it on ruby-doc.

At the top of our Ruby file we need to require the library:

require 'net/http'
Enter fullscreen mode Exit fullscreen mode

Once, the library is required we can begin making requests.

There are different types of requests in HTTP, expressed as verbs:

  • POST
  • GET
  • PUT
  • PATCH
  • DELETE

Each one of those verbs represents a different type of action you wish to perform. The Mozilla Docs has some good info on them.

We will build a GET request now, and for the rest of today, I encourage you to experiment with the other verbs!

uri = URI('https://dev.to/bengreenberg/49-days-of-ruby-day-33-creating-a-ruby-gem-44jc')

page = Net::HTTP.get(uri)

puts page
Enter fullscreen mode Exit fullscreen mode

In the above example, we first created a new URI using the web address for the blog post from #49daysofruby yesterday. (A URI is an identifier, or address, for a web resource.) Then, we made a GET request to that URI saving the results to a variable called page. Lastly, we outputted the results.

Try that in your terminal by starting an IRB session. Make sure, to enter require net/http first before you start.

You should see a whole lot of HTML, that's the blog from yesterday!

You just made your first HTTP request in Rub. Congrats!

Come back tomorrow for the next installment of 49 Days of Ruby! You can join the conversation on Twitter with the hashtag #49daysofruby.

Top comments (0)