Where developers come to connect, share, build and be inspired.

51

Use RestClient for HTTP requests in Ruby

10466 views

Using RestClient is a great way to make HTTP requests in Ruby. The usage is very easy and it supports some really awesome things like multipart encoding, proxying, self-signed certificates and much more! I'll show you some basic examples.

Example: simple GET request

require 'rest-client'
response = RestClient.get 'http://example.com'
puts response.code
→ 200
puts response.headers[:server]
→ Apache

Example: API GET request

require 'rest-client'
require 'json'
data = RestClient.get 'https://api.example.com/v1/items', { 'Authorization' => "Bearer #{@access_token}" }
data = JSON.parse(data)

Example: POST request with parameters

require 'rest-client'
post = RestClient.post 'http://example.com', {:params => {'page' => 'hello', 'world' => 'earth'}}
puts post.args[:payload][:params]
→ {"page"=>"hello", "world"=>"earth"}

Just use rubygems to get the gem:

gem install rest-client

Or you can get the source from Github (see comment below by endel).

Comments

Add a comment