You are on page 1of 47

Lightweight web services

with Sinatra and RestClient

Adam Wiggins &


Blake Mizerany
Rubyconf 2008
What for?
app lifecycle
Birth: small and beautiful
Fate: sprawling mess
web services
Rails?
Rails?

Too much.
Bare mongrel handler or
Rack app?
Bare mongrel handler or
Rack app?

Too little.
Sinatra - the classy
microframework for
Ruby
require 'rubygems'
require 'sinatra'

get '/' do
"Hello, whirled"
end
$ ruby hello.rb
require 'rubygems'
require 'sinatra'
require 'lib/posts'

post '/posts'
post = Post.create! params
redirect "/posts/#{post.id}"
do

get '/posts/:id' do
@post = Post.find(params[:id])
erb :post
end
‣Templating (erb, haml, builder)
‣Tests/specs (test/spec, rspec, test::unit)
‣Before filters
‣Helpers
‣Error handlers
‣Inline templates
‣Code reloading
‣HTTP caching (etag, last-modified)
‣Rack / inline middleware
A commitment to small
A commitment to small
Rails 87,990
Merb-core 12,417
Ramaze 11,796
Camping 1,704
Sinatra 1,576
Sinatra is a proud
Ruby citizen
examples
git-wiki
http://github.com/sr/git-wiki

355 lines
of Ruby
get '/:page' do
@page = Page.find(params[:page])
haml :show
end

__END__
@@ layout
%html
%body
%content=yield

@@ show
%h1= title
#page_content= @page.to_html
rifgraf
http://github.com/adamwiggins/rifgraf

61 lines
of Ruby
github-services
http://github.com/pjhyett/github-services

423 lines
of Ruby
scanty
http://github.com/adamwiggins/scanty

194 lines
of Ruby
client side
ActiveResource?
ActiveResource?

Too much.
Net::HTTP?
Net::HTTP?

Too little.
RestClient -
the Sinatra-inspired
microclient for Ruby
require 'rubygems'
require 'rest_client'

RestClient.get 'http://localhost:4567/posts'
require 'rubygems'
require 'rest_client'

RestClient.post 'http://localhost:4567/posts',
:author => 'Me', :title => 'First Post'
Console
$ restclient http://example.com
>> post '/resource', :value => 42
=> "result"
A better curl
$ restclient get http://example.com/posts > posts.xml

$ restclient post http://example.com/posts < post.xml

$ restclient put http://example.com/posts/1 < post.xml

$ restclient delete http://example.com/posts/1


Logging & replay
$ RESTCLIENT_LOG=stdout ruby myscript.rb

RestClient.get "http://example.com/posts"
# => 200 OK | text/html 3781 bytes

RestClient.post "http://example.com/posts",
"title=First+post"
# => 200 OK | text/html 40 bytes
examples
heroku-client
http://github.com/adamwiggins/heroku-client
couchrest
http://github.com/jchris/couchrest
principles
“lagom”
“lagom”
just the right amount
Fewer classes,
less inheritance
Controller object
mapping & routes
vs.
URLs
Controller object s !
RL
mapping & routes U e
r th
fea
vs.
n ’ t
o
URLs
D
Exposed simplicity
instead of
hidden complexity
Small things,
loosely joined,
written fast

- Justin Gehtland @ Relevance


http://github.com/bmizerany/sinatra
http://rest-client.heroku.com/

http://adam.blog.heroku.com/

Adam Wiggins &


Blake Mizerany
Rubyconf 2008