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

Galera Replication Demystified: How Does It Work?
Galera Replication Demystified: How Does It Work?Galera Replication Demystified: How Does It Work?
Galera Replication Demystified: How Does It Work?Frederic Descamps
 
간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기Kyoung Up Jung
 
gRPC vs REST: let the battle begin!
gRPC vs REST: let the battle begin!gRPC vs REST: let the battle begin!
gRPC vs REST: let the battle begin!Alex Borysov
 
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)Altinity Ltd
 
Securing AEM webapps by hacking them
Securing AEM webapps by hacking themSecuring AEM webapps by hacking them
Securing AEM webapps by hacking themMikhail Egorov
 
ProxySQL in the Cloud
ProxySQL in the CloudProxySQL in the Cloud
ProxySQL in the CloudRené Cannaò
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBMydbops
 
OWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsOWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsLewis Ardern
 
Pentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A PrimerPentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A PrimerBrian Hysell
 
MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼NeoClova
 
Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...
Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...
Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...Mario Heiderich
 
thymeleafさいしょの一歩
thymeleafさいしょの一歩thymeleafさいしょの一歩
thymeleafさいしょの一歩Yuichi Hasegawa
 
My sql failover test using orchestrator
My sql failover test  using orchestratorMy sql failover test  using orchestrator
My sql failover test using orchestratorYoungHeon (Roy) Kim
 
Writing a fast HTTP parser
Writing a fast HTTP parserWriting a fast HTTP parser
Writing a fast HTTP parserfukamachi
 
Hunting for security bugs in AEM webapps
Hunting for security bugs in AEM webappsHunting for security bugs in AEM webapps
Hunting for security bugs in AEM webappsMikhail Egorov
 
MySQL Timeout Variables Explained
MySQL Timeout Variables Explained MySQL Timeout Variables Explained
MySQL Timeout Variables Explained Mydbops
 

What's hot (20)

Galera Replication Demystified: How Does It Work?
Galera Replication Demystified: How Does It Work?Galera Replication Demystified: How Does It Work?
Galera Replication Demystified: How Does It Work?
 
간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기간단한 블로그를 만들며 Django 이해하기
간단한 블로그를 만들며 Django 이해하기
 
gRPC vs REST: let the battle begin!
gRPC vs REST: let the battle begin!gRPC vs REST: let the battle begin!
gRPC vs REST: let the battle begin!
 
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
 
Securing AEM webapps by hacking them
Securing AEM webapps by hacking themSecuring AEM webapps by hacking them
Securing AEM webapps by hacking them
 
MySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB StatusMySQL 5.5 Guide to InnoDB Status
MySQL 5.5 Guide to InnoDB Status
 
Ajax Ppt 1
Ajax Ppt 1Ajax Ppt 1
Ajax Ppt 1
 
ProxySQL in the Cloud
ProxySQL in the CloudProxySQL in the Cloud
ProxySQL in the Cloud
 
Parallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDBParallel Replication in MySQL and MariaDB
Parallel Replication in MySQL and MariaDB
 
OWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript ApplicationsOWASP SF - Reviewing Modern JavaScript Applications
OWASP SF - Reviewing Modern JavaScript Applications
 
Pentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A PrimerPentesting Modern Web Apps: A Primer
Pentesting Modern Web Apps: A Primer
 
MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼MariaDB MaxScale monitor 매뉴얼
MariaDB MaxScale monitor 매뉴얼
 
Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...
Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...
Copy & Pest - A case-study on the clipboard, blind trust and invisible cross-...
 
Query logging with proxysql
Query logging with proxysqlQuery logging with proxysql
Query logging with proxysql
 
thymeleafさいしょの一歩
thymeleafさいしょの一歩thymeleafさいしょの一歩
thymeleafさいしょの一歩
 
Building Advanced XSS Vectors
Building Advanced XSS VectorsBuilding Advanced XSS Vectors
Building Advanced XSS Vectors
 
My sql failover test using orchestrator
My sql failover test  using orchestratorMy sql failover test  using orchestrator
My sql failover test using orchestrator
 
Writing a fast HTTP parser
Writing a fast HTTP parserWriting a fast HTTP parser
Writing a fast HTTP parser
 
Hunting for security bugs in AEM webapps
Hunting for security bugs in AEM webappsHunting for security bugs in AEM webapps
Hunting for security bugs in AEM webapps
 
MySQL Timeout Variables Explained
MySQL Timeout Variables Explained MySQL Timeout Variables Explained
MySQL Timeout Variables Explained
 

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

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Recently uploaded (20)

My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

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