SlideShare a Scribd company logo
1 of 84
Download to read offline
No REST for the Wicked
An overview of REST and Catalyst
By Jay Shirley <jshirley@coldhardcode.com>




                                             1
REST in 5 Minutes



          No Dragons Here




                            2
What Is REST?

Using more of HTTP 1.1




                         3
What Is REST?

Using more of HTTP 1.1
A set of ideas
  Most are good
  Most are easy




                         3
What Isn’t REST

A defined protocol




                    4
What Isn’t REST

A defined protocol
A tool for every job




                       4
What Isn’t REST

A defined protocol
A tool for every job
Good for browsers
  Since IE7, most browsers work with XmlHttpRequest
  Various hacks exist to DTRT




                                                      4
HTTP does a lot
Common “verbs” for CRUD:
  Create an object (POST)
  Retrieve an object (GET)
  Update an object (PUT)
  Delete an object (DELETE)
(And more, but that’s another story)



                                       5
HTTP is Extensible

HTTP Headers:
   Content-type
   X-Your-Header
     X-AuthToken
     X-REST-Tunnel-Method (for dumb browsers)




                                                6
What about pretty URIs?

Pretty URI ≠ REST




                          7
What about pretty URIs?

Pretty URI ≠ REST
Functional URI = REST
  /item/B9B6F0F8-1DE5-11DD-9305-CB9FBFD82403
  (still REST)
  Pretty for the computer, not for you.




                                               7
So, REST is

Using as much of the HTTP spec as you can
With URIs that...




                                            8
So, REST is

Using as much of the HTTP spec as you can
With URIs that...
  Mean something (Represent a resource or object)




                                                    8
So, REST is

Using as much of the HTTP spec as you can
With URIs that...
  Mean something (Represent a resource or object)
  Don’t have to be pretty




                                                    8
So, REST is

Using as much of the HTTP spec as you can
With URIs that...
  Mean something (Represent a resource or object)
  Don’t have to be pretty
  Don’t have to be ugly




                                                    8
Oh, and...



        Stateless


                    9
Stateless?	

 Client holds the state
 Transactions get tricky
 Implicit trust of the client
 Trouble for web applications




                                10
Using REST


All or nothing? No, a la carte.
Not a standard; just good ideas
Use only what you need




                                  11
REST in more minutes...




                          12
REST is in the Request

Typical browser request:
  Host:   iwatchsoccer.com
  User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X
  10.5; en-US; rv:1.9b5) Gecko/2008032619 Firefox/3.0b5
  Accept: HTTP Accept=text/html,application/xhtml
  +xml,application/xml;q=0.9,*/*;q=0.8
  Accept-Language: en-us,en;q=0.5
  Accept-Encoding: gzip,deflate
  Accept-Charset:   ISO-8859-1,utf-8;q=0.7,*;q=0.7
  Keep-Alive: 300
  Connection: keep-alive



                                                          13
The response should
respect the request.




                       14
The response should
respect the request.
  “Accept” determines what serialization format
  (and “Content-Type”)




                                                  14
The response should
respect the request.
  “Accept” determines what serialization format
  (and “Content-Type”)
  “Accept-Language” determines what language




                                                  14
The response should
respect the request.
  “Accept” determines what serialization format
  (and “Content-Type”)
  “Accept-Language” determines what language
  “Accept-Charset” determines what charset




                                                  14
The response should
respect the request.
  “Accept” determines what serialization format
  (and “Content-Type”)
  “Accept-Language” determines what language
  “Accept-Charset” determines what charset
Listed in order of preference from the client.




                                                  14
And now for Catalyst




                       15
Catalyst::Action::REST
 Available from CPAN
 Handles:
   Accept (Response Format)
   Request (GET, PUT, POST, DELETE)
 Easy to configure
 Works great



                                      16
And to help out...




                     17
And to help out...
 Catalyst::Controller::REST::DBIC::Item
     • I couldn’t think of a longer name
     • Just a base class for yak shaving
     • Links DBIx::Class result sets to REST actions
     • Almost CRUD, except just scaffolding for it
     • Only a dev release on CPAN

         (only thing fancy about it is this slide)
                                                       17
A Use Case

         http://www.iwatchsoccer.com/


  A simple site to list upcoming soccer matches.
      Uses Catalyst, REST and DBIx::Class




                                                   18
Very small

                       Team   League


 Four Basic Objects:


                       Game   Game




                                       19
And some links

A game has many broadcasts
Networks have many broadcasts
A game belongs to a league
A team has many leagues




                                20
Using REST


Still works in a web browser
Serializes response through Template Toolkit
Handles GET only (but doesn’t have to)




                                               21
Handling other verbs

    POST, PUT, DELETE via simple commands:




                                             22
Handling other verbs

      POST, PUT, DELETE via simple commands:


$ POST -c ‘text/x-yaml’ http://localhost:3000/team




                                                     22
Handling other verbs

      POST, PUT, DELETE via simple commands:


$ POST -c ‘text/x-yaml’ http://localhost:3000/team
Please enter content (text/x-yaml) to be POSTed:
---
display_name: Urawa Red Diamonds




                                                     22
Perl:


 my $lwp = LWP::UserAgent->new;
 $lwp->post( quot;http://localhost:3000/teamquot;,
  'Content-type' => 'text/x-yaml',
    Content => YAML::Syck::Dump($team)
 );




                                             23
Same idea for GET




                    24
Same idea for GET
$ GET -H ‘Content-type: text/x-yaml’ 
   http://localhost:3000/team




                                         24
Same idea for GET
$ GET -H ‘Content-type: text/x-yaml’ 
   http://localhost:3000/team


---
 -
   display_name: Urawa Red Diamonds
   pk1: 7
   token_name: urawa-red-diamonds




                                         24
Just change Content-type




                           25
Just change Content-type
$ GET -H ‘Content-type: text/x-json’ 
   http://localhost:3000/team




                                         25
Just change Content-type
$ GET -H ‘Content-type: text/x-json’ 
   http://localhost:3000/team


[{quot;token_namequot;:quot;urawa-red-
diamondsquot;,quot;display_namequot;:quot;Urawa Red
Diamondsquot;,quot;pk1quot;:7}]




                                         25
Not just YAML




                26
Not just YAML
Many serialization formats, from Catalyst::Action::REST




                                                          26
Not just YAML
Many serialization formats, from Catalyst::Action::REST
    YAML




                                                          26
Not just YAML
Many serialization formats, from Catalyst::Action::REST
    YAML
    JSON




                                                          26
Not just YAML
Many serialization formats, from Catalyst::Action::REST
    YAML
    JSON
    XML::Simple




                                                          26
Not just YAML
Many serialization formats, from Catalyst::Action::REST
    YAML
    JSON
    XML::Simple
    Data::Serializer




                                                          26
Not just YAML
Many serialization formats, from Catalyst::Action::REST
    YAML
    JSON
    XML::Simple
    Data::Serializer
    Any Catalyst View



                                                          26
Not just YAML
Many serialization formats, from Catalyst::Action::REST
    YAML
    JSON
    XML::Simple
    Data::Serializer
    Any Catalyst View
    Easy to write your own


                                                          26
And, of course, HTML




                       27
Template Toolkit:




    “Serialization”
                      28
All through configuration:
 package MyApp::Controller::RestClass;
 ...
 __PACKAGE__->config(
     'default' => 'text/html',
     'map' => {
         'text/html' => [ 'View', 'TT' ],
         'text/xml' => [ 'View', 'TT' ]
     }
 );




                                            29
The REST Chain


Catalyst::DispatchType::Chained




                                  30
The REST Chain


Catalyst::DispatchType::Chained
  Very powerful




                                  30
The REST Chain


Catalyst::DispatchType::Chained
  Very powerful
  Not what this talk is about




                                  30
Starting the chain

 Two actions:
 sub rest_base : Chained(‘/’) PathPart(‘rest’)
     CaptureArgs(0) { }

 # Automatically defined by
 Catalyst::Controller::REST::DBIC::Item

 sub rest_item : Chained(‘rest_base’) PathPart(‘item’)
     CaptureArgs(1) { }




                                                         31
What you really need:

 package IWS::Controller::Team;
 use strict;
 use warnings;
 use base 'Catalyst::Controller::REST::DBIC::Item';
 __PACKAGE__->config(
      # snipped general REST config
      'class'    => 'Schema::Team',
      'item_key' => 'token_name',
      'serialize_method' => 'serialize',
      'browser_serialize' => 0
 );
 sub rest_base : Chained('/') PathPart('') CaptureArgs(0){ }

                                                               32
Simple Controllers
 sub rest_item_POST {

     my ( $self, $c ) = @_;

     my $data = $c->request->data;

     my $row = $self->get_rs( $c )->find_or_create($data);

     if ( $row ) {

         $self->status_created( $c, ... );

     } else {

         $self->status_bad_request( $c, ... );

     }

 }

                (but please, validate $data)
                                                             33
Dispatching REST Actions
Chain is:
rest_base -> rest_item -> rest_item_${METHOD}




                                                34
Dispatching REST Actions
Chain is:
rest_base -> rest_item -> rest_item_${METHOD}

  GET /rest/item/foo




                                                34
Dispatching REST Actions
Chain is:
rest_base -> rest_item -> rest_item_${METHOD}

  GET /rest/item/foo
    calls rest_item_GET




                                                34
Dispatching REST Actions
Chain is:
rest_base -> rest_item -> rest_item_${METHOD}

  GET /rest/item/foo
    calls rest_item_GET
  PUT /rest/item/foo




                                                34
Dispatching REST Actions
Chain is:
rest_base -> rest_item -> rest_item_${METHOD}

  GET /rest/item/foo
    calls rest_item_GET
  PUT /rest/item/foo
    calls rest_item_PUT




                                                34
Dispatching REST Actions
Chain is:
rest_base -> rest_item -> rest_item_${METHOD}

  GET /rest/item/foo
    calls rest_item_GET
  PUT /rest/item/foo
    calls rest_item_PUT
All from Catalyst::Action::REST



                                                34
Simple Controllers

 sub rest_item_DELETE {

     my ( $self, $c ) = @_;

     my $item = $c->stash->{rest}->{item};

     $item->delete;

     return $self->status_accepted( $c,

          entity => { status => ‘deleted’ }

     );

 }




                                              35
More Bling

Browsers and REST do not play well...




                                        36
More Bling

Browsers and REST do not play well...
  Except inside of XmlHttpRequest




                                        36
More Bling

Browsers and REST do not play well...
  Except inside of XmlHttpRequest
  With IE7, they all play well




                                        36
More Bling

Browsers and REST do not play well...
  Except inside of XmlHttpRequest
  With IE7, they all play well
  Full support of POST, PUT, GET and DELETE




                                              36
The Solution




http://developer.yahoo.com/yui/
                                  37
Why YUI?

Well supported
Smart hackers that know JavaScript
Smart hackers that know standards
Good documentation, code and primitives




                                          38
YUI REST Commands


YAHOO.util.Connect.asyncRequest(
     ‘PUT’, uri, callback, data
);




                                   39
Needs a few modifications


YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’);

YAHOO.util.Connect.asyncRequest(

     ‘PUT’, uri, callback, YAHOO.lang.JSON.stringify(data)

);




                                                             40
Still easy.




              41
Still easy.


 Set the content-type:
 YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’);




                                                           41
Still easy.


 Set the content-type:
 YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’);

 Stringify the data:
 YAHOO.lang.JSON.stringify(data)




                                                           41
Still easy.


 Set the content-type:
 YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’);

 Stringify the data:
 YAHOO.lang.JSON.stringify(data)

 Done




                                                           41
Connecting to a form

A few points:
  Form action does not need to be what you use in
  JavaScript
  Form method does not need to be what you use in
  JavaScript




                                                    42
YAHOO.util.Event


var form = YAHOO.util.Dom.get(‘form_id’);

YAHOO.util.Event.on( form, ‘submit’, function() {



});




                                                    43
That’s it


 Serialize form data into JSON
 Do PUT, POST, DELETE, GET on form submit
 REST




                                            44
A word on JSON
JSON is not:
  Supposed to be eval’d
  Just JavaScript




                          45
A word on JSON
JSON is not:
  Supposed to be eval’d
  Just JavaScript
JSON is:
  Very Fast (JSON::XS and JSON::PC)
  Very Small



                                      45

More Related Content

What's hot

{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4琛琳 饶
 
ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com琛琳 饶
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and DesktopElizabeth Smith
 
What you need to remember when you upload to CPAN
What you need to remember when you upload to CPANWhat you need to remember when you upload to CPAN
What you need to remember when you upload to CPANcharsbar
 
TorqueBox - When Java meets Ruby
TorqueBox - When Java meets RubyTorqueBox - When Java meets Ruby
TorqueBox - When Java meets RubyBruno Oliveira
 
Perl Memory Use - LPW2013
Perl Memory Use - LPW2013Perl Memory Use - LPW2013
Perl Memory Use - LPW2013Tim Bunce
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyTim Bunce
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principlesPerl Careers
 
Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011CodeIgniter Conference
 
Perl Memory Use 201209
Perl Memory Use 201209Perl Memory Use 201209
Perl Memory Use 201209Tim Bunce
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in VaultGlynnForrest
 
Solr for Indexing and Searching Logs
Solr for Indexing and Searching LogsSolr for Indexing and Searching Logs
Solr for Indexing and Searching LogsSematext Group, Inc.
 
DBD::Gofer 200809
DBD::Gofer 200809DBD::Gofer 200809
DBD::Gofer 200809Tim Bunce
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data CachingEl Taller Web
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by pythonwonyong hwang
 
Chapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDBChapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDBMongoDB
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUNCong Zhang
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12Tim Bunce
 

What's hot (20)

{{more}} Kibana4
{{more}} Kibana4{{more}} Kibana4
{{more}} Kibana4
 
ELK stack at weibo.com
ELK stack at weibo.comELK stack at weibo.com
ELK stack at weibo.com
 
Php on the Web and Desktop
Php on the Web and DesktopPhp on the Web and Desktop
Php on the Web and Desktop
 
What you need to remember when you upload to CPAN
What you need to remember when you upload to CPANWhat you need to remember when you upload to CPAN
What you need to remember when you upload to CPAN
 
TorqueBox - When Java meets Ruby
TorqueBox - When Java meets RubyTorqueBox - When Java meets Ruby
TorqueBox - When Java meets Ruby
 
Perl Memory Use - LPW2013
Perl Memory Use - LPW2013Perl Memory Use - LPW2013
Perl Memory Use - LPW2013
 
Application Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.keyApplication Logging in the 21st century - 2014.key
Application Logging in the 21st century - 2014.key
 
PSGI and Plack from first principles
PSGI and Plack from first principlesPSGI and Plack from first principles
PSGI and Plack from first principles
 
Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011Bottom to Top Stack Optimization - CICON2011
Bottom to Top Stack Optimization - CICON2011
 
Php on Windows
Php on WindowsPhp on Windows
Php on Windows
 
Perl Memory Use 201209
Perl Memory Use 201209Perl Memory Use 201209
Perl Memory Use 201209
 
Static Typing in Vault
Static Typing in VaultStatic Typing in Vault
Static Typing in Vault
 
Solr for Indexing and Searching Logs
Solr for Indexing and Searching LogsSolr for Indexing and Searching Logs
Solr for Indexing and Searching Logs
 
DBD::Gofer 200809
DBD::Gofer 200809DBD::Gofer 200809
DBD::Gofer 200809
 
Zend Server Data Caching
Zend Server Data CachingZend Server Data Caching
Zend Server Data Caching
 
BlockChain implementation by python
BlockChain implementation by pythonBlockChain implementation by python
BlockChain implementation by python
 
Chapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDBChapman: Building a High-Performance Distributed Task Service with MongoDB
Chapman: Building a High-Performance Distributed Task Service with MongoDB
 
Using ngx_lua in UPYUN
Using ngx_lua in UPYUNUsing ngx_lua in UPYUN
Using ngx_lua in UPYUN
 
Top Node.js Metrics to Watch
Top Node.js Metrics to WatchTop Node.js Metrics to Watch
Top Node.js Metrics to Watch
 
Perl at SkyCon'12
Perl at SkyCon'12Perl at SkyCon'12
Perl at SkyCon'12
 

Similar to No REST for the Wicked: Overview of REST and Catalyst

Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)vibrantuser
 
Use perl creating web services with xml rpc
Use perl creating web services with xml rpcUse perl creating web services with xml rpc
Use perl creating web services with xml rpcJohnny Pork
 
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014Puppet
 
Couchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemCouchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemdelagoya
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteDr Nic Williams
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbaiaadi Surve
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Karel Minarik
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHPZoran Jeremic
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
Bare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and ChefBare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and ChefMatt Ray
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...King Foo
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLUlf Wendel
 

Similar to No REST for the Wicked: Overview of REST and Catalyst (20)

Web Services Tutorial
Web Services TutorialWeb Services Tutorial
Web Services Tutorial
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)Sql php-vibrant course-mumbai(1)
Sql php-vibrant course-mumbai(1)
 
Sinatra for REST services
Sinatra for REST servicesSinatra for REST services
Sinatra for REST services
 
Use perl creating web services with xml rpc
Use perl creating web services with xml rpcUse perl creating web services with xml rpc
Use perl creating web services with xml rpc
 
REST in Peace
REST in PeaceREST in Peace
REST in Peace
 
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
Fully Automate Application Delivery with Puppet and F5 - PuppetConf 2014
 
Couchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problemCouchdb: No SQL? No driver? No problem
Couchdb: No SQL? No driver? No problem
 
RubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - KeynoteRubyEnRails2007 - Dr Nic Williams - Keynote
RubyEnRails2007 - Dr Nic Williams - Keynote
 
Php classes in mumbai
Php classes in mumbaiPhp classes in mumbai
Php classes in mumbai
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]
 
Rack
RackRack
Rack
 
Consuming RESTful Web services in PHP
Consuming RESTful Web services in PHPConsuming RESTful Web services in PHP
Consuming RESTful Web services in PHP
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Bare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and ChefBare Metal to OpenStack with Razor and Chef
Bare Metal to OpenStack with Razor and Chef
 
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
 
Restful webservices
Restful webservicesRestful webservices
Restful webservices
 
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQLHTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
HTTP, JSON, JavaScript, Map&Reduce built-in to MySQL
 
Node.js Workshop
Node.js WorkshopNode.js Workshop
Node.js Workshop
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
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
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
#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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
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
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
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
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
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
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
#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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

No REST for the Wicked: Overview of REST and Catalyst

  • 1. No REST for the Wicked An overview of REST and Catalyst By Jay Shirley <jshirley@coldhardcode.com> 1
  • 2. REST in 5 Minutes No Dragons Here 2
  • 3. What Is REST? Using more of HTTP 1.1 3
  • 4. What Is REST? Using more of HTTP 1.1 A set of ideas Most are good Most are easy 3
  • 5. What Isn’t REST A defined protocol 4
  • 6. What Isn’t REST A defined protocol A tool for every job 4
  • 7. What Isn’t REST A defined protocol A tool for every job Good for browsers Since IE7, most browsers work with XmlHttpRequest Various hacks exist to DTRT 4
  • 8. HTTP does a lot Common “verbs” for CRUD: Create an object (POST) Retrieve an object (GET) Update an object (PUT) Delete an object (DELETE) (And more, but that’s another story) 5
  • 9. HTTP is Extensible HTTP Headers: Content-type X-Your-Header X-AuthToken X-REST-Tunnel-Method (for dumb browsers) 6
  • 10. What about pretty URIs? Pretty URI ≠ REST 7
  • 11. What about pretty URIs? Pretty URI ≠ REST Functional URI = REST /item/B9B6F0F8-1DE5-11DD-9305-CB9FBFD82403 (still REST) Pretty for the computer, not for you. 7
  • 12. So, REST is Using as much of the HTTP spec as you can With URIs that... 8
  • 13. So, REST is Using as much of the HTTP spec as you can With URIs that... Mean something (Represent a resource or object) 8
  • 14. So, REST is Using as much of the HTTP spec as you can With URIs that... Mean something (Represent a resource or object) Don’t have to be pretty 8
  • 15. So, REST is Using as much of the HTTP spec as you can With URIs that... Mean something (Represent a resource or object) Don’t have to be pretty Don’t have to be ugly 8
  • 16. Oh, and... Stateless 9
  • 17. Stateless? Client holds the state Transactions get tricky Implicit trust of the client Trouble for web applications 10
  • 18. Using REST All or nothing? No, a la carte. Not a standard; just good ideas Use only what you need 11
  • 19. REST in more minutes... 12
  • 20. REST is in the Request Typical browser request: Host: iwatchsoccer.com User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9b5) Gecko/2008032619 Firefox/3.0b5 Accept: HTTP Accept=text/html,application/xhtml +xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive 13
  • 21. The response should respect the request. 14
  • 22. The response should respect the request. “Accept” determines what serialization format (and “Content-Type”) 14
  • 23. The response should respect the request. “Accept” determines what serialization format (and “Content-Type”) “Accept-Language” determines what language 14
  • 24. The response should respect the request. “Accept” determines what serialization format (and “Content-Type”) “Accept-Language” determines what language “Accept-Charset” determines what charset 14
  • 25. The response should respect the request. “Accept” determines what serialization format (and “Content-Type”) “Accept-Language” determines what language “Accept-Charset” determines what charset Listed in order of preference from the client. 14
  • 26. And now for Catalyst 15
  • 27. Catalyst::Action::REST Available from CPAN Handles: Accept (Response Format) Request (GET, PUT, POST, DELETE) Easy to configure Works great 16
  • 28. And to help out... 17
  • 29. And to help out... Catalyst::Controller::REST::DBIC::Item • I couldn’t think of a longer name • Just a base class for yak shaving • Links DBIx::Class result sets to REST actions • Almost CRUD, except just scaffolding for it • Only a dev release on CPAN (only thing fancy about it is this slide) 17
  • 30. A Use Case http://www.iwatchsoccer.com/ A simple site to list upcoming soccer matches. Uses Catalyst, REST and DBIx::Class 18
  • 31. Very small Team League Four Basic Objects: Game Game 19
  • 32. And some links A game has many broadcasts Networks have many broadcasts A game belongs to a league A team has many leagues 20
  • 33. Using REST Still works in a web browser Serializes response through Template Toolkit Handles GET only (but doesn’t have to) 21
  • 34. Handling other verbs POST, PUT, DELETE via simple commands: 22
  • 35. Handling other verbs POST, PUT, DELETE via simple commands: $ POST -c ‘text/x-yaml’ http://localhost:3000/team 22
  • 36. Handling other verbs POST, PUT, DELETE via simple commands: $ POST -c ‘text/x-yaml’ http://localhost:3000/team Please enter content (text/x-yaml) to be POSTed: --- display_name: Urawa Red Diamonds 22
  • 37. Perl: my $lwp = LWP::UserAgent->new; $lwp->post( quot;http://localhost:3000/teamquot;, 'Content-type' => 'text/x-yaml', Content => YAML::Syck::Dump($team) ); 23
  • 38. Same idea for GET 24
  • 39. Same idea for GET $ GET -H ‘Content-type: text/x-yaml’ http://localhost:3000/team 24
  • 40. Same idea for GET $ GET -H ‘Content-type: text/x-yaml’ http://localhost:3000/team --- - display_name: Urawa Red Diamonds pk1: 7 token_name: urawa-red-diamonds 24
  • 42. Just change Content-type $ GET -H ‘Content-type: text/x-json’ http://localhost:3000/team 25
  • 43. Just change Content-type $ GET -H ‘Content-type: text/x-json’ http://localhost:3000/team [{quot;token_namequot;:quot;urawa-red- diamondsquot;,quot;display_namequot;:quot;Urawa Red Diamondsquot;,quot;pk1quot;:7}] 25
  • 45. Not just YAML Many serialization formats, from Catalyst::Action::REST 26
  • 46. Not just YAML Many serialization formats, from Catalyst::Action::REST YAML 26
  • 47. Not just YAML Many serialization formats, from Catalyst::Action::REST YAML JSON 26
  • 48. Not just YAML Many serialization formats, from Catalyst::Action::REST YAML JSON XML::Simple 26
  • 49. Not just YAML Many serialization formats, from Catalyst::Action::REST YAML JSON XML::Simple Data::Serializer 26
  • 50. Not just YAML Many serialization formats, from Catalyst::Action::REST YAML JSON XML::Simple Data::Serializer Any Catalyst View 26
  • 51. Not just YAML Many serialization formats, from Catalyst::Action::REST YAML JSON XML::Simple Data::Serializer Any Catalyst View Easy to write your own 26
  • 52. And, of course, HTML 27
  • 53. Template Toolkit: “Serialization” 28
  • 54. All through configuration: package MyApp::Controller::RestClass; ... __PACKAGE__->config( 'default' => 'text/html', 'map' => { 'text/html' => [ 'View', 'TT' ], 'text/xml' => [ 'View', 'TT' ] } ); 29
  • 57. The REST Chain Catalyst::DispatchType::Chained Very powerful Not what this talk is about 30
  • 58. Starting the chain Two actions: sub rest_base : Chained(‘/’) PathPart(‘rest’) CaptureArgs(0) { } # Automatically defined by Catalyst::Controller::REST::DBIC::Item sub rest_item : Chained(‘rest_base’) PathPart(‘item’) CaptureArgs(1) { } 31
  • 59. What you really need: package IWS::Controller::Team; use strict; use warnings; use base 'Catalyst::Controller::REST::DBIC::Item'; __PACKAGE__->config( # snipped general REST config 'class' => 'Schema::Team', 'item_key' => 'token_name', 'serialize_method' => 'serialize', 'browser_serialize' => 0 ); sub rest_base : Chained('/') PathPart('') CaptureArgs(0){ } 32
  • 60. Simple Controllers sub rest_item_POST { my ( $self, $c ) = @_; my $data = $c->request->data; my $row = $self->get_rs( $c )->find_or_create($data); if ( $row ) { $self->status_created( $c, ... ); } else { $self->status_bad_request( $c, ... ); } } (but please, validate $data) 33
  • 61. Dispatching REST Actions Chain is: rest_base -> rest_item -> rest_item_${METHOD} 34
  • 62. Dispatching REST Actions Chain is: rest_base -> rest_item -> rest_item_${METHOD} GET /rest/item/foo 34
  • 63. Dispatching REST Actions Chain is: rest_base -> rest_item -> rest_item_${METHOD} GET /rest/item/foo calls rest_item_GET 34
  • 64. Dispatching REST Actions Chain is: rest_base -> rest_item -> rest_item_${METHOD} GET /rest/item/foo calls rest_item_GET PUT /rest/item/foo 34
  • 65. Dispatching REST Actions Chain is: rest_base -> rest_item -> rest_item_${METHOD} GET /rest/item/foo calls rest_item_GET PUT /rest/item/foo calls rest_item_PUT 34
  • 66. Dispatching REST Actions Chain is: rest_base -> rest_item -> rest_item_${METHOD} GET /rest/item/foo calls rest_item_GET PUT /rest/item/foo calls rest_item_PUT All from Catalyst::Action::REST 34
  • 67. Simple Controllers sub rest_item_DELETE { my ( $self, $c ) = @_; my $item = $c->stash->{rest}->{item}; $item->delete; return $self->status_accepted( $c, entity => { status => ‘deleted’ } ); } 35
  • 68. More Bling Browsers and REST do not play well... 36
  • 69. More Bling Browsers and REST do not play well... Except inside of XmlHttpRequest 36
  • 70. More Bling Browsers and REST do not play well... Except inside of XmlHttpRequest With IE7, they all play well 36
  • 71. More Bling Browsers and REST do not play well... Except inside of XmlHttpRequest With IE7, they all play well Full support of POST, PUT, GET and DELETE 36
  • 73. Why YUI? Well supported Smart hackers that know JavaScript Smart hackers that know standards Good documentation, code and primitives 38
  • 74. YUI REST Commands YAHOO.util.Connect.asyncRequest( ‘PUT’, uri, callback, data ); 39
  • 75. Needs a few modifications YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’); YAHOO.util.Connect.asyncRequest( ‘PUT’, uri, callback, YAHOO.lang.JSON.stringify(data) ); 40
  • 77. Still easy. Set the content-type: YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’); 41
  • 78. Still easy. Set the content-type: YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’); Stringify the data: YAHOO.lang.JSON.stringify(data) 41
  • 79. Still easy. Set the content-type: YAHOO.util.Connect.setDefaultPostHeader(‘text/x-json’); Stringify the data: YAHOO.lang.JSON.stringify(data) Done 41
  • 80. Connecting to a form A few points: Form action does not need to be what you use in JavaScript Form method does not need to be what you use in JavaScript 42
  • 81. YAHOO.util.Event var form = YAHOO.util.Dom.get(‘form_id’); YAHOO.util.Event.on( form, ‘submit’, function() { }); 43
  • 82. That’s it Serialize form data into JSON Do PUT, POST, DELETE, GET on form submit REST 44
  • 83. A word on JSON JSON is not: Supposed to be eval’d Just JavaScript 45
  • 84. A word on JSON JSON is not: Supposed to be eval’d Just JavaScript JSON is: Very Fast (JSON::XS and JSON::PC) Very Small 45