HTTP(Hypertext Transfer Protocol) is the fundamental protocol used to transfer data over the internet. An HTTP request typically contains three parts: the URL, headers and body. And this data is transferred using a specific method.
The GET and POST methods are most common types of request methods. Other methods include HEAD, PUT, DELETE, CONNECT, and OPTIONS.
The get method is used to request information from a web server, while the post method is used to send information to a web server. The data transmitted through the HTTP client is usually in text, JSON, or XML format.
Structure of an HTTP Request
An HTTP request consists of three parts:
1 . The request line: containing the method, uri and protocol version
2 . The header: containing the metadata (optional)
3 . The body: containing the data (optional)
There are multiple ways to implement an http request in Ruby, this section will look at the standard built-in HTTP library.
The Net::HTTP Library
Ruby has a built-in HTTP client that you can use to make requests to web servers. The Ruby HTTP client is a module called Net::HTTP. This module is used alongside the URI module. URI(Uniform Resource Identifier) contains two subsets, URN, which gives the name, and URL, which gives the location of the resource.
NB: When using net/http module, you don’t need to require ‘uri’ separately since net/http takes care of that.
The GET Request
This sends a GET request to the API endpoint located at typicode.com, that contains a list of users and their information.
If you run the file on the console like so:
You get the following results:
As you can see, the API here contains data that is serialized into JSON, therefore, you need to deserealize it into a hash object in order to work with it in Ruby. You should require the json library and then parse the result body like so:
After parsing it, you get:
A GET request may contain a header. The header provides additional information about the request in the form of a key-value pair. For instance, an API may require that you provide authentication details on the headers as shown below:
The POST Request
A POST request always has a body and sometimes both a header and a body. The body contains the payload.
Sending a post request is also simple:
However, the API that you are posting to may require that you configure your request to send appropriate headers. Unfortunately Net::HTTP’s post_form method doesn’t support headers.
The key to achieving that is to create a new Net::HTTP object and then send the headers hash as a third argument to its post method: