12.7. Using REST in Ruby

As with Python, sending HTTP requests in Ruby is extremely easy.

Issuing GET Requests
We use the class Net::HTTP to do all the magic:

require 'net/http'

url = 'http://www.acme.com/products/3322' # ACME boomerang
resp = Net::HTTP.get_response(URI.parse(url))

resp_text = resp.body

The response field code contains the HTTP response code. To make things simpler, the result object's very class indicates the response type; for example, resp (in the example above) will be of type Net::HTTPSuccess if the response is 2xx (HTTP OK code), or Net::HTTPNotFound for 404 responoses (HTTP Not Found code). A complete hierarchy of the response classes appears in Net::HTTP's documentation.

Issuing POST Requests
We need Net::HTTP's post_form method for POSTing:

require 'net/http'

url = 'http://www.acme.com/user/details'
params = {
  firstName => 'John',
  lastName => 'Doe
}

resp = Net::HTTP.post_form(url, params)

resp_text = resp.body

The form encoding is application/x-www-form-urlencoded by default.

0 comments: