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.


Sidu said...

I've been working on a fluent ruby HTTP/REST library called Wrest for some time now. Do take a look and let me know what you think.

Dr. M. Elkstein said...

Hello Sidu,

I wish you luck in your Wrest library (neat name!). However, I cannot spare the time, at the moment, to properly review it.

talk said...

Hi there,

Great site. BTW: you are missing a dash after Doe

Dr. M. Elkstein said...

Hi 'talk',

Thank you! I've fixed that now.