Wrest

© Copyright 2009 Sidu Ponnappa. All Rights Reserved.

Wrest is a ruby REST client library which allows you to quickly build object oriented wrappers around any web service. It has two components - Wrest Core and Wrest::Resource.

If you were wondering why the words ‘demon’, ‘chi’ and ‘puppies’ (among others) show up in nearly every example and spec, it’s because they all refer to characters and ideas from Roger Zelazny’s last book, ‘Lord Demon.’

Wrest Core: Features

  • Provides convenient HTTP wrappers, serialisation and deserialisation with caching and redirect handling in the works.

  • Designed to be used as a library, not just a command line REST client (fewer class methods, more object oriented)

  • Isn’t coupled to Rails (usable in a pure Ruby application to consume any HTTP/REST api)

  • Can be used both stand alone as well as to build object oriented abstractions around resources and web services (Wrest::Resource is an example of the latter)

Examples

See github.com/kaiwren/wrest/tree/master/examples

Installation

The source is available at git://github.com/kaiwren/wrest.git

To install as a Rails plugin, do script/plugin install git://github.com/kaiwren/wrest.git

To install the Wrest gem, do (sudo) gem install wrest

Wrest is also available as a gem for JRuby; you can instally it by running (sudo) jruby -S gem install wrest.

Usage: Shell

You can launch the interactive Wrest shell by running bin/wrest if you have the source or invoking wrest from your prompt if you’ve installed the gem.

$ wrest
>> y 'http://twitter.com/statuses/public_timeline.json'.to_uri.get.deserialise

Usage: Library

require 'rubygems'
require 'wrest'
y "http://search.yahooapis.com/NewsSearchService/V1/newsSearch".to_uri.get(

:appid => ‘YahooDemo’, :output => ‘xml’, :query => ‘India’, :results=> ‘3’, :start => ‘1’ )

Usage: Basic Http Calls

GET

A couple of ways to get Yahoo news as a hash map.

  • This example simply does a get on a uri and figures out the appropriate deserialiser using the content-type (in this case ‘text/javascript’, which uses Wrest::Translators::Json). See content_types.rb under lib/wrest/mappers/translators.

"http://search.yahooapis.com/NewsSearchService/V1/newsSearch?appid=YahooDemo&output=json&query=India&results=3&start=1".to_uri.get.deserialise
  • This example does a get on a base uri with several parameters passed to it, resulting in a uri essentially the same as the one above. It also shows how you can specify a custom deserialiser to produce a hash-map from the response, as well as a hash mutator to clean up the deserialised hash.

require 'rubygems'
require 'wrest'
include Wrest::Components
y "http://search.yahooapis.com/NewsSearchService/V1/newsSearch".to_uri.get(

:appid => ‘YahooDemo’, :output => ‘xml’, :query => ‘India’, :results=> ‘3’, :start => ‘1’ ).deserialise_using( Translators::Xml ).mutate_using( Mutators::XmlMiniTypeCaster.new )

DELETE

To delete a resource:

'https://api.del.icio.us/v1/posts/delete'.to_uri(
                                             :username => 'kaiwren',
                                             :password => 'fupupp1es'
                                           ).delete(
                                             :url => 'http://c2.com'
                                           )

OPTIONS

To find out what actions are permitted on a URI:

'http://www.yahoo.com'.to_uri.options.headers['allow']

Usage: Attributes Container

Allows any class to hold an attributes hash, somewhat like ActiveResource. It also supports several extensions to this base fuctionality such as support for typecasting attribute values.

Example:

class Demon
  include Wrest::Components::AttributesContainer
  include Wrest::Components::AttributesContainer::Typecaster

  always_has	      :id  
  typecast         :age          =>  as_integer,
                   :chi          =>  lambda{|chi| Chi.new(chi)}
end

kai_wren = Demon.new('id => '1', 'age' => '1500', 'chi' => '1024', 'teacher' => 'Viss')
kai_wren.id			# => '1'
kai_wren.age			# => 1500
kai_wren.chi			# => #<Chi:0x113af8c @count="1024">
kai_wren.teacher		# => 'Viss'

Usage: Logging

The Wrest logger can be set and accessed through Wrest.logger and is configured by default to log to STDOUT. If you’re using Wrest in a Rails application, you can configure logging by placing the following line in your environment file:

Wrest.logger = ActiveRecord::Base.logger

Build

Standard options are available and can be listed using rake -T. Use rake:rcov for coverage and rake:rdoc to generate documentation.

Documentation

Wrest RDocs can be found at wrest.rubyforge.org

Wrest::Resource

Wrest::Resource is an alternative to Rails’ ActiveResource. It targets Rails REST (well, POX, since Rails isn’t really RESTful) services and is currently under development. Since no single REST library can provide an object oriented wrapper suitable for all available web services, it follows that Wrest should focus on providing you with the tools to help you roll your own. Wrest::Resource is an example of this - an object oriented wrapper for the kind of REST APIs exposed by Rails applications, that you would otherwise use ActiveResource to consume.

  • No more pretending that REST resources are the same as records in a database (yeah, no more freaking ActiveResource::Connection)

  • Treat put as ‘create or update,’ not just ‘update’

  • Response codes result in user defined state transitions; favours state transitions based on response code over arbitrary ones

  • Supports moving toward hypermedia links as opposed to client server collusion through URI templates

  • The header is now exposed as metadata, rather being than something you have no control over

  • Out of the box support for If-Unmodified-Since/If-Match+Etag

  • Out of the box support for collections

  • Out of the box support for collection pagination (including support for WillPaginate), both header based and xml attribute based

  • Out of the box support for operations on all the records on the collection

  • Out of the box support for nested resources

  • Out of the box support for cached resources

  • Out of the box support for type-casting data that comes in as parameter strings

  • More natural mapping of deserialised entities to existing classes

  • No communication via exceptions for http error status codes

  • Better extensibility - allows access to request/response objects, avoids class variables, favours symbols over strings etc.

  • Content Types in request headers

  • Consider support for OPTIONS and response codes 100/417

Dependencies

Source

  • gems

  • json (json-jruby on JRuby)

  • active_support

  • ruby-libxml (Recommended, will fall back to REXML if absent; be aware that Wrest uses ActiveSupport::XmlMini, so if you’re using Wrest as a plugin in a Rails application, all xml parsing across the application will switch to using libxml if it’s available. You’re free to change this by hand by using the ActiveSupport::XmlMini.backend= method.)

Build

  • rspec

  • rcov (unsupported on JRuby)

  • jeweler

Support

This project uses Assembla for ticketing: www.assembla.com/spaces/wrest/tickets

Licence

Wrest is released under the Apache 2.0 licence