SlideShare a Scribd company logo
1 of 62
REST with Sinatra
  Emanuele DelBono
      @emadb
Thanks to the sponsors
About me
I’m a software developer in
CodicePlastico.
I write Web applications in C# with
ASP.NET MVC. I’m a member of
<WEBdeBS/> a local web
community.
...and I’m a wannabe Ruby
developer ;-)
Agenda
‣ Philosophy.
 Sweet and easy.
‣ REST.
 Yet another boring introduction.
‣ Hello world.
 Show some magic.
‣ Features.
 Amazing!
‣ Inside.
 How it works?
‣ Q&A.
 ...and thanks.
Sinatra as a REST server
What is isn’t
‣ Sinatra is not
 -another MV* framework
 -a full framework like Rails
 -an ORM
 -a game project
Sinatra is just a DSL
   written in ruby
Hello world
Hello world
~$ gem install sinatra
~$ vi app.rb
Hello world
~$ gem install sinatra
~$ vi app.rb

require 'sinatra'
get '/' do
 'hello world!'
end
Hello world
~$ gem install sinatra
~$ vi app.rb

require 'sinatra'
get '/' do
 'hello world!'
end

~$ ruby app.rb
Is it really so easy?
‣ Yep! (special thanks to Ruby
  sweeties)
  - get is a just a method (more later)
  - the route is the parameter
  - the block is what should be
    executed
  - the block returns the result
  - the server is built in (based on Rack)
Let’s go REST


What? Yet another REST introduction?
5 REST principles
‣ Uniform Interface
    ‣ HATEAOS
‣   Stateless
‣   Cacheable
‣   Client-Server
‣   Layered System
Sinatra and REST
‣ Sinatra supports
  - All HTTP verbs
  - Caching
  - Content types
  - Routes
  - ....and all you need to build a rest server
Give a look at the
Verbs
‣ Support for all verbs
  - Get, Post, Put, Delete, Head, Options,
    Patch


‣ They are just methods
Routing
‣ No need of route files or route
  maps
‣ The verb method takes the route
  as parameter
Routing


get ( ‘/todos’ ) {...}
get ( ‘/todo/:id’ ) {...}
get ( ‘/*’ ) {...}
Routing Conditions
get '/foo', :agent => /Mozilla/(d.d)s
w?/ do
 "You're using Mozilla version
#{params[:agent][0]}"
end
get '/foo' do
 # Matches non-Mozilla browsers
end
Routing Custom
set(:prob) { |v| condition { rand <= v } }

get '/win_a_car', :prob => 0.1 do
 "You won!"
end

get '/win_a_car' {"Sorry, you lost."}
Xml or Json
‣ You can set the content_type to
  whatever you need



content_type :json
content_type :xml
Status codes
‣ Set the HTTP status code is


  status 200
  status 403
Http Headers
‣ You can add your own headers


headers "X-My-Value" => "this is my
header"
Redirect


redirect to ‘/todos’
Cache
‣ You can set your cache information
  using the headers method

headers "Cache-Control" => "public,
must-revalidate, max-age=3600",
"Expires" => Time.at(Time.now.to_i + (60
Cache
‣ Or better, you can use the expires


expires 3600, :public
Filters
before do
 #...
end
after do
 #...
Authentication


‣ Basic authentication support through
  Rack
‣ Key-based authentication
Basic Authentication

use Rack::Auth::Basic, "Private area" do
|usr, pwd|
 [usr, pwd] == ['admin', 'admin']
end
Token authentication
before do
 if env[‘HTTP_MY_KEY’] ==’rubyrocks‘
   error 401
 end
end
Demo
Stream
‣ Supports streamed content
‣ Streamed responses have no Content-
  Length header
‣ But have Transfer-Encoding: chunked
Inside
Inside
‣ Sinatra source code is on github:
    http://github.com/sinatra/sinatra
‣ Less than 2k lines of code
‣ Based on Rack
Application style


Classic application
         vs
Modular application
Classic App

  Single file
 Standalone
Modular Apps


         Multi file
Subclassing Sinatra::Base
  Distributed as library
The code
What happen when a request arrives?


get (‘/hello’) do { ‘hello world’ }
Where do get come from?
require "sinatra"
outer_self = self
get '/' do
 "outer self: #{outer_self}, inner self: #{self}"
end


 outer self: main, inner self: #<Sinatra::Application:

        closures in ruby are “scope gate”
$ irb
$ irb
ruby-1.9.2-p180 > require 'sinatra'
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
=> Sinatra::Application
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
=> Sinatra::Application
ruby-1.9.2-p180 > Sinatra::Application.method(:get)
$ irb
ruby-1.9.2-p180 > require 'sinatra'
=> true
ruby-1.9.2-p180 > method(:get)
=> #<Method: Object(Sinatra::Delegator)#get>
ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
=> [:delegate, :target, :target=]
ruby-1.9.2-p180 > Sinatra::Delegator.target
=> Sinatra::Application
ruby-1.9.2-p180 > Sinatra::Application.method(:get)
=> #<Method:
Sinatra::Application(Sinatra::Base).get>
Where do get come from?
‣ get is defined twice:
  – Once in Sinatra::Delegator a mixin
    extending Object
  – Once in Sinatra::Application
‣ The Delegator implementation simply
  delegate to Application
‣ That’s why we have get/post/...
  methods on main
How the block is invoked?
‣ The route! method finds the correct
  route

def route_eval
 throw :halt, yield
end

‣ throw is used to go back to the invoker
In base.rb

‣ The invoker


def invoke
 res = catch(:halt) { yield }
 # .... other code...
end
It’s a kind of magic!
Sinatra has ended his set
    (crowd applauds)
Questions?
demos at:
http://github.com/emadb/
     webnetconf_demo
Please rate this session
Scan the code, go online, rate this session

More Related Content

What's hot

Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVCNathaniel Richand
 
Integration Testing with a Citrus twist
Integration Testing with a Citrus twistIntegration Testing with a Citrus twist
Integration Testing with a Citrus twistchristophd
 
Introduction to mvc architecture
Introduction to mvc architectureIntroduction to mvc architecture
Introduction to mvc architectureravindraquicsolv
 
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...Alex Cachia
 
Clean architecture
Clean architectureClean architecture
Clean architectureLieven Doclo
 
Design Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityDesign Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityMudasir Qazi
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Svetlin Nakov
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring bootAntoine Rey
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaCODE WHITE GmbH
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing ArchitecturesVictor Rentea
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#Bohdan Pashkovskyi
 
Web hacking-dvwa-publish-130131073605-phpapp01
Web hacking-dvwa-publish-130131073605-phpapp01Web hacking-dvwa-publish-130131073605-phpapp01
Web hacking-dvwa-publish-130131073605-phpapp01Jalil Mashab-Crew
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Svetlin Nakov
 
Implementing DDD with C#
Implementing DDD with C#Implementing DDD with C#
Implementing DDD with C#Pascal Laurin
 

What's hot (20)

Presentation Spring, Spring MVC
Presentation Spring, Spring MVCPresentation Spring, Spring MVC
Presentation Spring, Spring MVC
 
Integration Testing with a Citrus twist
Integration Testing with a Citrus twistIntegration Testing with a Citrus twist
Integration Testing with a Citrus twist
 
Introduction to mvc architecture
Introduction to mvc architectureIntroduction to mvc architecture
Introduction to mvc architecture
 
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
No Onions, No Tiers - An Introduction to Vertical Slice Architecture by Bill ...
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Design Pattern - Chain of Responsibility
Design Pattern - Chain of ResponsibilityDesign Pattern - Chain of Responsibility
Design Pattern - Chain of Responsibility
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
Cryptography for Java Developers: Nakov jProfessionals (Jan 2019)
 
Onion architecture
Onion architectureOnion architecture
Onion architecture
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Introduction à spring boot
Introduction à spring bootIntroduction à spring boot
Introduction à spring boot
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
Vertical Slicing Architectures
Vertical Slicing ArchitecturesVertical Slicing Architectures
Vertical Slicing Architectures
 
Asynchronous programming in C#
Asynchronous programming in C#Asynchronous programming in C#
Asynchronous programming in C#
 
Web hacking-dvwa-publish-130131073605-phpapp01
Web hacking-dvwa-publish-130131073605-phpapp01Web hacking-dvwa-publish-130131073605-phpapp01
Web hacking-dvwa-publish-130131073605-phpapp01
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
Architectural Patterns and Software Architectures: Client-Server, Multi-Tier,...
 
Implementing DDD with C#
Implementing DDD with C#Implementing DDD with C#
Implementing DDD with C#
 

Similar to Sinatra for REST services

Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Servicevvatikiotis
 
Socket applications
Socket applicationsSocket applications
Socket applicationsJoão Moura
 
Swing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and SinatraSwing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and SinatraMatt Gifford
 
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Alberto Perdomo
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxbobmcwhirter
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统yiditushe
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hopeMarcus Ramberg
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发shaokun
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebookguoqing75
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with PuppetKris Buytaert
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmsom_nangia
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpmwilburlo
 

Similar to Sinatra for REST services (20)

Sinatra and JSONQuery Web Service
Sinatra and JSONQuery Web ServiceSinatra and JSONQuery Web Service
Sinatra and JSONQuery Web Service
 
infra-as-code
infra-as-codeinfra-as-code
infra-as-code
 
Socket applications
Socket applicationsSocket applications
Socket applications
 
Mojolicious
MojoliciousMojolicious
Mojolicious
 
PSGI/Plack OSDC.TW
PSGI/Plack OSDC.TWPSGI/Plack OSDC.TW
PSGI/Plack OSDC.TW
 
Swing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and SinatraSwing when you're winning - an introduction to Ruby and Sinatra
Swing when you're winning - an introduction to Ruby and Sinatra
 
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
Strangers In The Night: Ruby, Rack y Sinatra - Herramientas potentes para con...
 
Complex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBoxComplex Made Simple: Sleep Better with TorqueBox
Complex Made Simple: Sleep Better with TorqueBox
 
Rack
RackRack
Rack
 
Wider than rails
Wider than railsWider than rails
Wider than rails
 
Facebook的缓存系统
Facebook的缓存系统Facebook的缓存系统
Facebook的缓存系统
 
Mojolicious - A new hope
Mojolicious - A new hopeMojolicious - A new hope
Mojolicious - A new hope
 
Sprockets
SprocketsSprockets
Sprockets
 
Sinatra
SinatraSinatra
Sinatra
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook4069180 Caching Performance Lessons From Facebook
4069180 Caching Performance Lessons From Facebook
 
Automating Complex Setups with Puppet
Automating Complex Setups with PuppetAutomating Complex Setups with Puppet
Automating Complex Setups with Puppet
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Psgi Plack Sfpm
Psgi Plack SfpmPsgi Plack Sfpm
Psgi Plack Sfpm
 
Plack - LPW 2009
Plack - LPW 2009Plack - LPW 2009
Plack - LPW 2009
 

More from Emanuele DelBono

More from Emanuele DelBono (13)

The simplest thing that could possibly work
The simplest thing that could possibly workThe simplest thing that could possibly work
The simplest thing that could possibly work
 
Una crescita armoniosa
Una crescita armoniosaUna crescita armoniosa
Una crescita armoniosa
 
A sip of Elixir
A sip of ElixirA sip of Elixir
A sip of Elixir
 
React.js in real world apps.
React.js in real world apps. React.js in real world apps.
React.js in real world apps.
 
An introduction to React.js
An introduction to React.jsAn introduction to React.js
An introduction to React.js
 
From ActiveRecord to EventSourcing
From ActiveRecord to EventSourcingFrom ActiveRecord to EventSourcing
From ActiveRecord to EventSourcing
 
Ruby seen by a C# developer
Ruby seen by a C# developerRuby seen by a C# developer
Ruby seen by a C# developer
 
Ruby loves DDD
Ruby loves DDDRuby loves DDD
Ruby loves DDD
 
An introduction to knockout.js
An introduction to knockout.jsAn introduction to knockout.js
An introduction to knockout.js
 
Node azure
Node azureNode azure
Node azure
 
Da programmatore a CEO
Da programmatore a CEODa programmatore a CEO
Da programmatore a CEO
 
Test driving an MVVM App
Test driving an MVVM AppTest driving an MVVM App
Test driving an MVVM App
 
Mocking
MockingMocking
Mocking
 

Recently uploaded

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Sinatra for REST services

  • 1. REST with Sinatra Emanuele DelBono @emadb
  • 2. Thanks to the sponsors
  • 3. About me I’m a software developer in CodicePlastico. I write Web applications in C# with ASP.NET MVC. I’m a member of <WEBdeBS/> a local web community. ...and I’m a wannabe Ruby developer ;-)
  • 4. Agenda ‣ Philosophy. Sweet and easy. ‣ REST. Yet another boring introduction. ‣ Hello world. Show some magic. ‣ Features. Amazing! ‣ Inside. How it works? ‣ Q&A. ...and thanks.
  • 5. Sinatra as a REST server
  • 6. What is isn’t ‣ Sinatra is not -another MV* framework -a full framework like Rails -an ORM -a game project
  • 7. Sinatra is just a DSL written in ruby
  • 9. Hello world ~$ gem install sinatra ~$ vi app.rb
  • 10. Hello world ~$ gem install sinatra ~$ vi app.rb require 'sinatra' get '/' do 'hello world!' end
  • 11. Hello world ~$ gem install sinatra ~$ vi app.rb require 'sinatra' get '/' do 'hello world!' end ~$ ruby app.rb
  • 12.
  • 13. Is it really so easy? ‣ Yep! (special thanks to Ruby sweeties) - get is a just a method (more later) - the route is the parameter - the block is what should be executed - the block returns the result - the server is built in (based on Rack)
  • 14. Let’s go REST What? Yet another REST introduction?
  • 15.
  • 16. 5 REST principles ‣ Uniform Interface ‣ HATEAOS ‣ Stateless ‣ Cacheable ‣ Client-Server ‣ Layered System
  • 17. Sinatra and REST ‣ Sinatra supports - All HTTP verbs - Caching - Content types - Routes - ....and all you need to build a rest server
  • 18. Give a look at the
  • 19. Verbs ‣ Support for all verbs - Get, Post, Put, Delete, Head, Options, Patch ‣ They are just methods
  • 20. Routing ‣ No need of route files or route maps ‣ The verb method takes the route as parameter
  • 21. Routing get ( ‘/todos’ ) {...} get ( ‘/todo/:id’ ) {...} get ( ‘/*’ ) {...}
  • 22. Routing Conditions get '/foo', :agent => /Mozilla/(d.d)s w?/ do "You're using Mozilla version #{params[:agent][0]}" end get '/foo' do # Matches non-Mozilla browsers end
  • 23. Routing Custom set(:prob) { |v| condition { rand <= v } } get '/win_a_car', :prob => 0.1 do "You won!" end get '/win_a_car' {"Sorry, you lost."}
  • 24. Xml or Json ‣ You can set the content_type to whatever you need content_type :json content_type :xml
  • 25. Status codes ‣ Set the HTTP status code is status 200 status 403
  • 26. Http Headers ‣ You can add your own headers headers "X-My-Value" => "this is my header"
  • 28. Cache ‣ You can set your cache information using the headers method headers "Cache-Control" => "public, must-revalidate, max-age=3600", "Expires" => Time.at(Time.now.to_i + (60
  • 29. Cache ‣ Or better, you can use the expires expires 3600, :public
  • 31. Authentication ‣ Basic authentication support through Rack ‣ Key-based authentication
  • 32. Basic Authentication use Rack::Auth::Basic, "Private area" do |usr, pwd| [usr, pwd] == ['admin', 'admin'] end
  • 33. Token authentication before do if env[‘HTTP_MY_KEY’] ==’rubyrocks‘ error 401 end end
  • 34. Demo
  • 35. Stream ‣ Supports streamed content ‣ Streamed responses have no Content- Length header ‣ But have Transfer-Encoding: chunked
  • 37. Inside ‣ Sinatra source code is on github: http://github.com/sinatra/sinatra ‣ Less than 2k lines of code ‣ Based on Rack
  • 38. Application style Classic application vs Modular application
  • 39. Classic App Single file Standalone
  • 40. Modular Apps Multi file Subclassing Sinatra::Base Distributed as library
  • 41. The code What happen when a request arrives? get (‘/hello’) do { ‘hello world’ }
  • 42. Where do get come from? require "sinatra" outer_self = self get '/' do "outer self: #{outer_self}, inner self: #{self}" end outer self: main, inner self: #<Sinatra::Application: closures in ruby are “scope gate”
  • 43.
  • 44. $ irb
  • 45. $ irb ruby-1.9.2-p180 > require 'sinatra'
  • 46. $ irb ruby-1.9.2-p180 > require 'sinatra' => true
  • 47. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get)
  • 48. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get>
  • 49. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false)
  • 50. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=]
  • 51. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target
  • 52. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target => Sinatra::Application
  • 53. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target => Sinatra::Application ruby-1.9.2-p180 > Sinatra::Application.method(:get)
  • 54. $ irb ruby-1.9.2-p180 > require 'sinatra' => true ruby-1.9.2-p180 > method(:get) => #<Method: Object(Sinatra::Delegator)#get> ruby-1.9.2-p180 > Sinatra::Delegator.methods(false) => [:delegate, :target, :target=] ruby-1.9.2-p180 > Sinatra::Delegator.target => Sinatra::Application ruby-1.9.2-p180 > Sinatra::Application.method(:get) => #<Method: Sinatra::Application(Sinatra::Base).get>
  • 55. Where do get come from? ‣ get is defined twice: – Once in Sinatra::Delegator a mixin extending Object – Once in Sinatra::Application ‣ The Delegator implementation simply delegate to Application ‣ That’s why we have get/post/... methods on main
  • 56. How the block is invoked? ‣ The route! method finds the correct route def route_eval throw :halt, yield end ‣ throw is used to go back to the invoker
  • 57. In base.rb ‣ The invoker def invoke res = catch(:halt) { yield } # .... other code... end
  • 58. It’s a kind of magic!
  • 59. Sinatra has ended his set (crowd applauds)
  • 62. Please rate this session Scan the code, go online, rate this session

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n