SlideShare a Scribd company logo
CakeFest 2012



                           Create a RESTful api
                                        Sept 1, 2012
CakeFest 2012 Manchester
INTRODUCTION




                           Marc Ypes
                              @Ceeram


                          CakePHP 4 years
                         Core team 1.5 years
                      Undercover as programmer


CakeFest 2012 Manchester
OVERVIEW

 REST my case?
 REST your Cake

 ■    Content-type
 ■    Routing
 ■    Interface
 ■    Authentication
 ■    Cache
 ■    Errors


CakeFest 2012 Manchester
INTRODUCTION TO REST
 Representational state transfer

 Set of architectural principles

 - resource focussed
 - manipulation through representations
 - HTTP protocol?




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Constraints

 ■    Client-server
 ■    Stateless
 ■    Uniform interface
 ■    Cacheable
 ■    Layered system




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform interface

 ■ resource

 ■ identification of the resource

 ■ manipulation through representation

 ■ self-descriptive

 ■ hypermedia as the engine of application state
   HATEOAS
CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 Data element                Example
 resource                    user, book etc. (users, books etc.)
 resource identifier         URL, URN (/users/1234)
 representation
    data                     TXT / HTML / XML /YAML,JSON
    metadata                 content type, last-modified time
 resource metadata           source link, alternate
 control data                if-modified-since, cache-control, etag


 http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm


CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 /api/getUserProfile/1234
 /api/addVoteForUser?id=1234
 /api/users?action=vote&id=1234
 /api/deleteUser/1
 /api/deleteUser?id=1
 /api/favoritedUsers
 /api/getUserData/1?fields=name,email


CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 GET                 /users        Get collection
 POST                /users        Add to collection
 GET                 /users/1234   Get resource
 PUT                 /users/1234   Update resource
 DELETE              /users/1234   Delete resource

 Update is not update?
 POST       /users/1234

CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 Typical request:

 >GET /books/1849511926 HTTP/1.1
 >Host: api.amazin.com
 >Accept: application/json

 >If-Modified-Since: Sat, 01 Sep 2012 10:22:36 GMT



CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 Typical response:

 < HTTP/1.1 200 OK
 < Date: Sat, 01 Sep 2012 11:45:12 GMT
 < Server: Apache/2.2.16 (Debian)
 < Last-Modified: Sat, 01 Sep 2012 11:25:31 GMT
 < Content-Length: 145
 < Content-Type: application/json
 {"book":{........"}}
CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 Typical response:

 < HTTP/1.1 304 Not Modified
 < Date: Sat, 01 Sep 2012 11:45:12 GMT
 < Server: Apache/2.2.16 (Debian)
 < Vary: Accept-Encoding




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 Safe methods
 Idempotent methods

 GET (HEAD) is safe (nullipotent)
 PUT, DELETE are idempotent

 POST
 PATCH?

CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 Normalize the resources

 GET            /books/1849511926/votes

 GET            /votes?book=1849511926




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 Normalize the resources

 POST                      /books/1849511926/votes

 PUT          /books/1849511926
 data contains votes subresource data

 POST         /votes
 data is book=1849511926

CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface

 PATCH

 Edge Rails: PATCH is the new primary HTTP method for updates




 http://weblog.rubyonrails.org/2012/2/25/edge-rails-patch-is-the-new-primary-http-method-for-updates/



CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 Level 3 of REST maturity model (RMM)




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 Level 0

 Single URI, single HTTP method




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 Level 1

 Many URI, single HTTP method




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 Level 2

 Many URI, different HTTP methods




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 Level 2

 Many URI, different HTTP methods




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 Level 3

 Self descriptive
 ■ Media types
 ■ Links
 ■ Other protocols




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 HATEOAS

 GET            /comments?book=1849511926

 Link to api.amazin.com/books/1849511926

 Links to all comments


CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS
 >GET      /comments/1
 <HTTP/1.1 200 Ok
 <Content-Type: text/xml
 <?xml version="1.0">
 <comment>
    <foo>great book</foo>
    <book>
       <link href="/books/1849511926" title="wow" />
    </book>
 </vote>
CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS
      {
           "foo":"bar",
           "book":
               {
                   "links":[
                       {
                            "href":"/book/1849511926",
                            "title":"wow"
                       }
                   ]
               }
      }
CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / HATEOAS

 Link header

 Link: <https://api.github.com/user/repos?page=2&per_page=100>;rel="
 next",
  <https://api.github.com/user/repos?page=50&per_page=100>;rel="last"




                               github.com
CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / Errors

 HTTP Statuscodes

 Human reads message
 Code reads code




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / Errors

 HTTP Statuscodes

 200 OK
 201 Created
 204 No Content
 304 Not Modified
 400 Bad Request
 401 Unauthorized
 404 Not Found
 405 Method Not Allowed
CakeFest 2012 Manchester
INTRODUCTION TO REST
 Uniform Interface / Errors

 Link to support page

 Link: <http://api.amazin.com/errors/405>; rel="help"




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Cacheable

 HTTP Cache headers

 Use them!




CakeFest 2012 Manchester
INTRODUCTION TO REST
 Cacheable

 HTTP Cache headers

 Cache-control
 - private
 - public
 - max-age / s-maxage
 - must-revalidate
 - nocache


CakeFest 2012 Manchester
INTRODUCTION TO REST
 Cacheable

 HTTP Cache validation

 Etag                          RS
 Last-Modified                 RS

 If-Modified-Since             RQ
 If-None-Match                 RQ

 If-Match                      RQ

CakeFest 2012 Manchester
INTRODUCTION TO REST


 REST might not be what you are looking for

 Questions?

 Rest my Cake




CakeFest 2012 Manchester
REST my Cake
 Basic setup

 Route urls with extensions
 http://localhost/cats/index.json

 app/Config/routes.php
 <?php
 // allow any url extension
 Router::parseExtensions();

 //or allow .json extension only
 Router::parseExtensions('json');

CakeFest 2012 Manchester
REST my Cake
 Basic setup

 Add RequestHandler component
 <?php
 App::uses('Controller', 'Controller');

 class AppController extends Controller {

     public $components = array(
        'DebugKit.Toolbar',
        'Session',
        'RequestHandler',
     );
 }

CakeFest 2012 Manchester
REST my Cake
 Basic setup

 Create view files, the CakePHP 1.3 way (almost)

 app/View/Cats/json/index.ctp

 <?php echo json_encode($cats) ;?>




CakeFest 2012 Manchester
REST my Cake
 Basic setup

 Use auto serialization, the CakePHP 2.x way

     public function view($id = null) {
       $this->Cat->id = $id;
       if (!$this->Cat->exists()) {
            throw new NotFoundException(__('Invalid cat'));
       }
       $this->set('cat', $this->Cat->read(null, $id));
       $this->set('_serialize', array('cat'));
     }
CakeFest 2012 Manchester
REST my Cake
 http://localhost/cats/index.json




CakeFest 2012 Manchester
REST my Cake
 http://localhost/cats/view/1.json




CakeFest 2012 Manchester
REST my Cake
 REST Routing

 Resource mapping

 http://localhost/cats
 http://localhost/cats/1

 app/Config/routes.php

 Router::mapResources(array('Cats', 'Users'));


CakeFest 2012 Manchester
REST my Cake
 REST Routing

 Resource mapping


 GET                       /cats     index()
 POST                      /cats     add()
 GET                       /cats/1   view(1)
 POST                      /cats/1   edit(1)
 PUT                       /cats/1   edit(1)
 DELETE                    /cats/1   delete(1)

CakeFest 2012 Manchester
REST my Cake
 REST Routing

 Resource mapping

 X-HTTP-Method-Override
 <Limit PUT DELETE>
  order deny,allow
  allow from all
 </Limit>


CakeFest 2012 Manchester
REST my Cake
 REST Routing

 Resource mapping
 app/Config/routes.php
 Router::resourceMap(array(
     array('action' => 'index','method' => 'GET','id' => false),
     array('action' => 'read','method' => 'GET','id' => true),
     array('action' => 'add','method' => 'POST','id' => false),
     array('action' => 'edit','method' => 'POST','id' => true),
     array('action' => 'replace','method' => 'PUT','id' => true),
     array('action' => 'update','method' => 'PATCH','id' => true),
     array('action' => 'delete','method' => 'DELETE','id' => true)
     array('action' => 'truncate','method'=>'DELETE','id'=>false)
 ));
CakeFest 2012 Manchester
REST my Cake
 REST Routing

 Resource mapping
 app/Config/routes.php
 Router::mapResources(
    array('Cats', 'Users', 'Pizza.Orders')
 );



 /cats         => CatsController::index() in app
 /users        => UsersController::index() in app
 /pizza/orders => OrdersController::index() in Pizza plugin
CakeFest 2012 Manchester
REST my Cake
 REST Routing

 Resource mapping
 app/Config/routes.php
 Router::mapResources(
    array('Cats', 'Users', 'Pizza.Orders'),
    array('prefix' => '/api/')
 );


 /api/cats           => CatsController::index() in app
 /api/users          => UsersController::index() in app
 /api/orders         => OrdersController::index() in Pizza plugin
CakeFest 2012 Manchester
REST my Cake
 REST Routing

 Resource mapping
 app/Config/routes.php
 Router::mapResources(
    array('Cats', 'Users', 'Pizza.Orders'),
    array('prefix' => '/api/, 'id' => Router::UUID')
 );


 /api/cats           => CatsController::index() in app
 /api/users          => UsersController::index() in app
 /api/orders         => OrdersController::index() in Pizza plugin
CakeFest 2012 Manchester
REST my Cake
 REST Routing



 .json
 ?format=json

 curl -H "Accept: application/json" http://localhost/cats




CakeFest 2012 Manchester
REST my Cake
 REST Routing


 GET /cats/sleeping
 GET /cats?status=sleeping
 GET /cats?sleeping=1


 GET /posts/recent
 GET /posts?type=recent


CakeFest 2012 Manchester
REST my Cake
 REST Routing

 /posts/foo/bar routes with passed params
 /posts/foo:bar routes with named params
 app/Config/routes.php
 Router::connect('/api/cats/*',
     array(
        'plugin' => null,
        'controller' => 'posts',
        'action' => 'index',
        '[method]' => 'GET'
 ));
CakeFest 2012 Manchester
REST my Cake
 REST Routing

 GET      /users/vote/1234
 POST /users/vote/1234 $this->Html->postLink()
 POST /api/users/1234/votes
 public function vote($id = null) {
   //user id exist, httpmethod checks etc.
   $this->User->updateAll(
       array('User.votes' => 'User.votes + 1'),
       array('User.id' => $id)
   );
 }
CakeFest 2012 Manchester
REST my Cake
 REST Routing

 POST /users/1234/votes
 app/Config/routes.php
 Router::connect('/api/users/:id/votes',
    array(
        'plugin' => null,
        'controller' => 'users',
        'action' => 'vote',
        '[method]' => 'POST'
    ),
    array('id' => Router::ID, 'pass' => 'id')
 );
CakeFest 2012 Manchester
REST my Cake
 REST Routing

 POST /users/1234/votes
 public function vote($id = null) {
   //user id exist checks etc
   $this->User->Vote->add($id);
 }
 POST /votes
 public function add() {
   $this->Vote->add($this->request->data['Vote.
 user']);
 }

CakeFest 2012 Manchester
REST my Cake
 REST Routing

 CakeRequest::addDetector(
     'patch',
     array(
        'env' => 'REQUEST_METHOD',
        'value' => 'PATCH'
 ));



CakeFest 2012 Manchester
REST my Cake
 CakeResponse

 header( $header = NULL, $value = NULL )
 send( )
 statusCode( $code = NULL )
 type( $contentType = NULL )




CakeFest 2012 Manchester
REST my Cake
 CakeResponse

 cache( $since, $time = '+1 day' )
 checkNotModified( $request )
 disableCache( )
 etag( $tag = NULL, $weak = false )
 expires( $time = NULL )
 maxAge( $seconds = NULL )
 modified( $time = NULL )
 mustRevalidate( $enable = NULL )
 notModified( )
 sharable( $public = NULL, $time = NULL )
 sharedMaxAge( $seconds = NULL )
CakeFest 2012 Manchester
REST my Cake
 RequestHandlerComponent

 public $components = array(
    'RequestHandler' => array(
       'viewClassMap' => array(
           'json' => 'RestJson',
           'xml' => 'RestXml'
       )
    )
 );
CakeFest 2012 Manchester
REST my Cake
 Authentication

 Public
 Api-key
 Basic Auth
 OAuth




CakeFest 2012 Manchester
REST my Cake
 Authentication

 public function getUser(CakeRequest $request) {
     if (!empty($this->settings['header'])) {
           $token = $request->header($this->settings['header']);
           if ($token) {
                 return $this->_findUser($token, null);
           }
     }
     if (!empty($request->query[$this->settings['parameter']])) {
           $token = $request->query[$this->settings['parameter']];
           return $this->_findUser($token);
     }
     return false;
 }


CakeFest 2012 Manchester
REST my Cake
 Versioning

 /rest
 /v1




CakeFest 2012 Manchester
REST my Cake




                           THANKS


CakeFest 2012 Manchester

More Related Content

What's hot

Rail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendranRail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendran
SPRITLE SOFTWARE PRIVATE LIMIT ED
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
Taha Malampatti
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
Abdul Malik Ikhsan
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
Samantha Geitz
 
Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2
Sumy PHP User Grpoup
 
Psr-7
Psr-7Psr-7
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
Michael Peacock
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
Caldera Labs
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
Aravindharamanan S
 
Hdfs connector
Hdfs connectorHdfs connector
Hdfs connector
kiranvanga
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
Shubhani Jain
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
Carol McDonald
 
Web api
Web apiWeb api
Web api
udaiappa
 
Slim Framework
Slim FrameworkSlim Framework
Slim Framework
Pramod Raghav
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
Umair Amjad
 
Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2
Sumy PHP User Grpoup
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
Geethu Mohan
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
mirahman
 

What's hot (20)

Rail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendranRail3 intro 29th_sep_surendran
Rail3 intro 29th_sep_surendran
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept Implementation
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2Service approach for development Rest API in Symfony2
Service approach for development Rest API in Symfony2
 
Psr-7
Psr-7Psr-7
Psr-7
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel Passport
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST API
 
Rest hello world_tutorial
Rest hello world_tutorialRest hello world_tutorial
Rest hello world_tutorial
 
Hdfs connector
Hdfs connectorHdfs connector
Hdfs connector
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
Web api
Web apiWeb api
Web api
 
Slim Framework
Slim FrameworkSlim Framework
Slim Framework
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3
 
Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2Service approach for development REST API in Symfony2
Service approach for development REST API in Symfony2
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
 

Similar to Cake fest 2012 create a restful api

Amsterdam php create a restful api
Amsterdam php create a restful apiAmsterdam php create a restful api
Amsterdam php create a restful api
ceeram
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
Mario Cardinal
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
Chalermpon Areepong
 
11 asp.net web api
11 asp.net web api11 asp.net web api
11 asp.net web api
Michael Mieles Caballero
 
I got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't oneI got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't one
Adrian Cole
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
Ido Flatow
 
RESTEasy
RESTEasyRESTEasy
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
JBug Italy
 
REST and Web API
REST and Web APIREST and Web API
REST and Web API
IT Weekend
 
REST and Web API
REST and Web APIREST and Web API
REST and Web API
Roman Kalita
 
Great APIs - Future of Your Progress App
Great APIs - Future of Your Progress AppGreat APIs - Future of Your Progress App
Great APIs - Future of Your Progress App
Gabriel Lucaciu
 
OData for iOS developers
OData for iOS developersOData for iOS developers
OData for iOS developers
Glen Gordon
 
SharePoint 2013 REST APIs
SharePoint 2013 REST APIsSharePoint 2013 REST APIs
SharePoint 2013 REST APIs
Giuseppe Marchi
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
hazzaz
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
Kerry Buckley
 
Web api
Web apiWeb api
About REST & Symfony
About REST & SymfonyAbout REST & Symfony
About REST & Symfony
Maxence Poutord
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
Maýur Chourasiya
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudh
Anirudh Bhatnagar
 
RESTful WCF Services
RESTful WCF ServicesRESTful WCF Services
RESTful WCF Services
Harish Ranganathan
 

Similar to Cake fest 2012 create a restful api (20)

Amsterdam php create a restful api
Amsterdam php create a restful apiAmsterdam php create a restful api
Amsterdam php create a restful api
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
11 asp.net web api
11 asp.net web api11 asp.net web api
11 asp.net web api
 
I got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't oneI got 99 problems, but ReST ain't one
I got 99 problems, but ReST ain't one
 
ASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP FundamentalsASP.NET Web API and HTTP Fundamentals
ASP.NET Web API and HTTP Fundamentals
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 
REST and Web API
REST and Web APIREST and Web API
REST and Web API
 
REST and Web API
REST and Web APIREST and Web API
REST and Web API
 
Great APIs - Future of Your Progress App
Great APIs - Future of Your Progress AppGreat APIs - Future of Your Progress App
Great APIs - Future of Your Progress App
 
OData for iOS developers
OData for iOS developersOData for iOS developers
OData for iOS developers
 
SharePoint 2013 REST APIs
SharePoint 2013 REST APIsSharePoint 2013 REST APIs
SharePoint 2013 REST APIs
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Web api
Web apiWeb api
Web api
 
About REST & Symfony
About REST & SymfonyAbout REST & Symfony
About REST & Symfony
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudh
 
RESTful WCF Services
RESTful WCF ServicesRESTful WCF Services
RESTful WCF Services
 

Recently uploaded

The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
Axel Rennoch
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
Adam Dunkels
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Nicolás Lopéz
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
Ivanti
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
aakash malhotra
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
Google Developer Group - Harare
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
Priyanka Aash
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
Jimmy Lai
 
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptxIntroduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
313mohammedarshad
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Kunal Gupta
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
maigasapphire
 
Figma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdfFigma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdf
Management Institute of Skills Development
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
HackersList
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
Priyanka Aash
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
ldtexsolbl
 
CiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.pptCiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.ppt
moinahousna
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Muhammad Ali
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
Zilliz
 

Recently uploaded (20)

The importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT StandardizationThe importance of Quality Assurance for ICT Standardization
The importance of Quality Assurance for ICT Standardization
 
How to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptxHow to Build a Profitable IoT Product.pptx
How to Build a Profitable IoT Product.pptx
 
Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024Vertex AI Agent Builder - GDG Alicante - Julio 2024
Vertex AI Agent Builder - GDG Alicante - Julio 2024
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
July Patch Tuesday
July Patch TuesdayJuly Patch Tuesday
July Patch Tuesday
 
Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024Three New Criminal Laws in India 1 July 2024
Three New Criminal Laws in India 1 July 2024
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
 
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
(CISOPlatform Summit & SACON 2024) Keynote _ Power Digital Identities With AI...
 
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python CodebaseEuroPython 2024 - Streamlining Testing in a Large Python Codebase
EuroPython 2024 - Streamlining Testing in a Large Python Codebase
 
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptxIntroduction-to-the-IAM-Platform-Implementation-Plan.pptx
Introduction-to-the-IAM-Platform-Implementation-Plan.pptx
 
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptxDublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
Dublin_mulesoft_meetup_Mulesoft_Salesforce_Integration (1).pptx
 
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
Girls Call Churchgate 9910780858 Provide Best And Top Girl Service And No1 in...
 
Figma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdfFigma AI Design Generator_ In-Depth Review.pdf
Figma AI Design Generator_ In-Depth Review.pdf
 
WhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring AppsWhatsApp Spy Online Trackers and Monitoring Apps
WhatsApp Spy Online Trackers and Monitoring Apps
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
(CISOPlatform Summit & SACON 2024) Digital Personal Data Protection Act.pdf
 
Types of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technologyTypes of Weaving loom machine & it's technology
Types of Weaving loom machine & it's technology
 
CiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.pptCiscoIconsLibrary cours de réseau VLAN.ppt
CiscoIconsLibrary cours de réseau VLAN.ppt
 
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
Litestack talk at Brighton 2024 (Unleashing the power of SQLite for Ruby apps)
 
Using LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and MilvusUsing LLM Agents with Llama 3, LangGraph and Milvus
Using LLM Agents with Llama 3, LangGraph and Milvus
 

Cake fest 2012 create a restful api

  • 1. CakeFest 2012 Create a RESTful api Sept 1, 2012 CakeFest 2012 Manchester
  • 2. INTRODUCTION Marc Ypes @Ceeram CakePHP 4 years Core team 1.5 years Undercover as programmer CakeFest 2012 Manchester
  • 3. OVERVIEW REST my case? REST your Cake ■ Content-type ■ Routing ■ Interface ■ Authentication ■ Cache ■ Errors CakeFest 2012 Manchester
  • 4. INTRODUCTION TO REST Representational state transfer Set of architectural principles - resource focussed - manipulation through representations - HTTP protocol? CakeFest 2012 Manchester
  • 5. INTRODUCTION TO REST Constraints ■ Client-server ■ Stateless ■ Uniform interface ■ Cacheable ■ Layered system CakeFest 2012 Manchester
  • 6. INTRODUCTION TO REST Uniform interface ■ resource ■ identification of the resource ■ manipulation through representation ■ self-descriptive ■ hypermedia as the engine of application state HATEOAS CakeFest 2012 Manchester
  • 7. INTRODUCTION TO REST Uniform Interface Data element Example resource user, book etc. (users, books etc.) resource identifier URL, URN (/users/1234) representation data TXT / HTML / XML /YAML,JSON metadata content type, last-modified time resource metadata source link, alternate control data if-modified-since, cache-control, etag http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm CakeFest 2012 Manchester
  • 8. INTRODUCTION TO REST Uniform Interface /api/getUserProfile/1234 /api/addVoteForUser?id=1234 /api/users?action=vote&id=1234 /api/deleteUser/1 /api/deleteUser?id=1 /api/favoritedUsers /api/getUserData/1?fields=name,email CakeFest 2012 Manchester
  • 9. INTRODUCTION TO REST Uniform Interface GET /users Get collection POST /users Add to collection GET /users/1234 Get resource PUT /users/1234 Update resource DELETE /users/1234 Delete resource Update is not update? POST /users/1234 CakeFest 2012 Manchester
  • 10. INTRODUCTION TO REST Uniform Interface Typical request: >GET /books/1849511926 HTTP/1.1 >Host: api.amazin.com >Accept: application/json >If-Modified-Since: Sat, 01 Sep 2012 10:22:36 GMT CakeFest 2012 Manchester
  • 11. INTRODUCTION TO REST Uniform Interface Typical response: < HTTP/1.1 200 OK < Date: Sat, 01 Sep 2012 11:45:12 GMT < Server: Apache/2.2.16 (Debian) < Last-Modified: Sat, 01 Sep 2012 11:25:31 GMT < Content-Length: 145 < Content-Type: application/json {"book":{........"}} CakeFest 2012 Manchester
  • 12. INTRODUCTION TO REST Uniform Interface Typical response: < HTTP/1.1 304 Not Modified < Date: Sat, 01 Sep 2012 11:45:12 GMT < Server: Apache/2.2.16 (Debian) < Vary: Accept-Encoding CakeFest 2012 Manchester
  • 13. INTRODUCTION TO REST Uniform Interface Safe methods Idempotent methods GET (HEAD) is safe (nullipotent) PUT, DELETE are idempotent POST PATCH? CakeFest 2012 Manchester
  • 14. INTRODUCTION TO REST Uniform Interface Normalize the resources GET /books/1849511926/votes GET /votes?book=1849511926 CakeFest 2012 Manchester
  • 15. INTRODUCTION TO REST Uniform Interface Normalize the resources POST /books/1849511926/votes PUT /books/1849511926 data contains votes subresource data POST /votes data is book=1849511926 CakeFest 2012 Manchester
  • 16. INTRODUCTION TO REST Uniform Interface PATCH Edge Rails: PATCH is the new primary HTTP method for updates http://weblog.rubyonrails.org/2012/2/25/edge-rails-patch-is-the-new-primary-http-method-for-updates/ CakeFest 2012 Manchester
  • 17. INTRODUCTION TO REST Uniform Interface / HATEOAS Level 3 of REST maturity model (RMM) CakeFest 2012 Manchester
  • 18. INTRODUCTION TO REST Uniform Interface / HATEOAS Level 0 Single URI, single HTTP method CakeFest 2012 Manchester
  • 19. INTRODUCTION TO REST Uniform Interface / HATEOAS Level 1 Many URI, single HTTP method CakeFest 2012 Manchester
  • 20. INTRODUCTION TO REST Uniform Interface / HATEOAS Level 2 Many URI, different HTTP methods CakeFest 2012 Manchester
  • 21. INTRODUCTION TO REST Uniform Interface / HATEOAS Level 2 Many URI, different HTTP methods CakeFest 2012 Manchester
  • 22. INTRODUCTION TO REST Uniform Interface / HATEOAS Level 3 Self descriptive ■ Media types ■ Links ■ Other protocols CakeFest 2012 Manchester
  • 23. INTRODUCTION TO REST Uniform Interface / HATEOAS HATEOAS GET /comments?book=1849511926 Link to api.amazin.com/books/1849511926 Links to all comments CakeFest 2012 Manchester
  • 24. INTRODUCTION TO REST Uniform Interface / HATEOAS >GET /comments/1 <HTTP/1.1 200 Ok <Content-Type: text/xml <?xml version="1.0"> <comment> <foo>great book</foo> <book> <link href="/books/1849511926" title="wow" /> </book> </vote> CakeFest 2012 Manchester
  • 25. INTRODUCTION TO REST Uniform Interface / HATEOAS { "foo":"bar", "book": { "links":[ { "href":"/book/1849511926", "title":"wow" } ] } } CakeFest 2012 Manchester
  • 26. INTRODUCTION TO REST Uniform Interface / HATEOAS Link header Link: <https://api.github.com/user/repos?page=2&per_page=100>;rel=" next", <https://api.github.com/user/repos?page=50&per_page=100>;rel="last" github.com CakeFest 2012 Manchester
  • 27. INTRODUCTION TO REST Uniform Interface / Errors HTTP Statuscodes Human reads message Code reads code CakeFest 2012 Manchester
  • 28. INTRODUCTION TO REST Uniform Interface / Errors HTTP Statuscodes 200 OK 201 Created 204 No Content 304 Not Modified 400 Bad Request 401 Unauthorized 404 Not Found 405 Method Not Allowed CakeFest 2012 Manchester
  • 29. INTRODUCTION TO REST Uniform Interface / Errors Link to support page Link: <http://api.amazin.com/errors/405>; rel="help" CakeFest 2012 Manchester
  • 30. INTRODUCTION TO REST Cacheable HTTP Cache headers Use them! CakeFest 2012 Manchester
  • 31. INTRODUCTION TO REST Cacheable HTTP Cache headers Cache-control - private - public - max-age / s-maxage - must-revalidate - nocache CakeFest 2012 Manchester
  • 32. INTRODUCTION TO REST Cacheable HTTP Cache validation Etag RS Last-Modified RS If-Modified-Since RQ If-None-Match RQ If-Match RQ CakeFest 2012 Manchester
  • 33. INTRODUCTION TO REST REST might not be what you are looking for Questions? Rest my Cake CakeFest 2012 Manchester
  • 34. REST my Cake Basic setup Route urls with extensions http://localhost/cats/index.json app/Config/routes.php <?php // allow any url extension Router::parseExtensions(); //or allow .json extension only Router::parseExtensions('json'); CakeFest 2012 Manchester
  • 35. REST my Cake Basic setup Add RequestHandler component <?php App::uses('Controller', 'Controller'); class AppController extends Controller { public $components = array( 'DebugKit.Toolbar', 'Session', 'RequestHandler', ); } CakeFest 2012 Manchester
  • 36. REST my Cake Basic setup Create view files, the CakePHP 1.3 way (almost) app/View/Cats/json/index.ctp <?php echo json_encode($cats) ;?> CakeFest 2012 Manchester
  • 37. REST my Cake Basic setup Use auto serialization, the CakePHP 2.x way public function view($id = null) { $this->Cat->id = $id; if (!$this->Cat->exists()) { throw new NotFoundException(__('Invalid cat')); } $this->set('cat', $this->Cat->read(null, $id)); $this->set('_serialize', array('cat')); } CakeFest 2012 Manchester
  • 38. REST my Cake http://localhost/cats/index.json CakeFest 2012 Manchester
  • 39. REST my Cake http://localhost/cats/view/1.json CakeFest 2012 Manchester
  • 40. REST my Cake REST Routing Resource mapping http://localhost/cats http://localhost/cats/1 app/Config/routes.php Router::mapResources(array('Cats', 'Users')); CakeFest 2012 Manchester
  • 41. REST my Cake REST Routing Resource mapping GET /cats index() POST /cats add() GET /cats/1 view(1) POST /cats/1 edit(1) PUT /cats/1 edit(1) DELETE /cats/1 delete(1) CakeFest 2012 Manchester
  • 42. REST my Cake REST Routing Resource mapping X-HTTP-Method-Override <Limit PUT DELETE> order deny,allow allow from all </Limit> CakeFest 2012 Manchester
  • 43. REST my Cake REST Routing Resource mapping app/Config/routes.php Router::resourceMap(array( array('action' => 'index','method' => 'GET','id' => false), array('action' => 'read','method' => 'GET','id' => true), array('action' => 'add','method' => 'POST','id' => false), array('action' => 'edit','method' => 'POST','id' => true), array('action' => 'replace','method' => 'PUT','id' => true), array('action' => 'update','method' => 'PATCH','id' => true), array('action' => 'delete','method' => 'DELETE','id' => true) array('action' => 'truncate','method'=>'DELETE','id'=>false) )); CakeFest 2012 Manchester
  • 44. REST my Cake REST Routing Resource mapping app/Config/routes.php Router::mapResources( array('Cats', 'Users', 'Pizza.Orders') ); /cats => CatsController::index() in app /users => UsersController::index() in app /pizza/orders => OrdersController::index() in Pizza plugin CakeFest 2012 Manchester
  • 45. REST my Cake REST Routing Resource mapping app/Config/routes.php Router::mapResources( array('Cats', 'Users', 'Pizza.Orders'), array('prefix' => '/api/') ); /api/cats => CatsController::index() in app /api/users => UsersController::index() in app /api/orders => OrdersController::index() in Pizza plugin CakeFest 2012 Manchester
  • 46. REST my Cake REST Routing Resource mapping app/Config/routes.php Router::mapResources( array('Cats', 'Users', 'Pizza.Orders'), array('prefix' => '/api/, 'id' => Router::UUID') ); /api/cats => CatsController::index() in app /api/users => UsersController::index() in app /api/orders => OrdersController::index() in Pizza plugin CakeFest 2012 Manchester
  • 47. REST my Cake REST Routing .json ?format=json curl -H "Accept: application/json" http://localhost/cats CakeFest 2012 Manchester
  • 48. REST my Cake REST Routing GET /cats/sleeping GET /cats?status=sleeping GET /cats?sleeping=1 GET /posts/recent GET /posts?type=recent CakeFest 2012 Manchester
  • 49. REST my Cake REST Routing /posts/foo/bar routes with passed params /posts/foo:bar routes with named params app/Config/routes.php Router::connect('/api/cats/*', array( 'plugin' => null, 'controller' => 'posts', 'action' => 'index', '[method]' => 'GET' )); CakeFest 2012 Manchester
  • 50. REST my Cake REST Routing GET /users/vote/1234 POST /users/vote/1234 $this->Html->postLink() POST /api/users/1234/votes public function vote($id = null) { //user id exist, httpmethod checks etc. $this->User->updateAll( array('User.votes' => 'User.votes + 1'), array('User.id' => $id) ); } CakeFest 2012 Manchester
  • 51. REST my Cake REST Routing POST /users/1234/votes app/Config/routes.php Router::connect('/api/users/:id/votes', array( 'plugin' => null, 'controller' => 'users', 'action' => 'vote', '[method]' => 'POST' ), array('id' => Router::ID, 'pass' => 'id') ); CakeFest 2012 Manchester
  • 52. REST my Cake REST Routing POST /users/1234/votes public function vote($id = null) { //user id exist checks etc $this->User->Vote->add($id); } POST /votes public function add() { $this->Vote->add($this->request->data['Vote. user']); } CakeFest 2012 Manchester
  • 53. REST my Cake REST Routing CakeRequest::addDetector( 'patch', array( 'env' => 'REQUEST_METHOD', 'value' => 'PATCH' )); CakeFest 2012 Manchester
  • 54. REST my Cake CakeResponse header( $header = NULL, $value = NULL ) send( ) statusCode( $code = NULL ) type( $contentType = NULL ) CakeFest 2012 Manchester
  • 55. REST my Cake CakeResponse cache( $since, $time = '+1 day' ) checkNotModified( $request ) disableCache( ) etag( $tag = NULL, $weak = false ) expires( $time = NULL ) maxAge( $seconds = NULL ) modified( $time = NULL ) mustRevalidate( $enable = NULL ) notModified( ) sharable( $public = NULL, $time = NULL ) sharedMaxAge( $seconds = NULL ) CakeFest 2012 Manchester
  • 56. REST my Cake RequestHandlerComponent public $components = array( 'RequestHandler' => array( 'viewClassMap' => array( 'json' => 'RestJson', 'xml' => 'RestXml' ) ) ); CakeFest 2012 Manchester
  • 57. REST my Cake Authentication Public Api-key Basic Auth OAuth CakeFest 2012 Manchester
  • 58. REST my Cake Authentication public function getUser(CakeRequest $request) { if (!empty($this->settings['header'])) { $token = $request->header($this->settings['header']); if ($token) { return $this->_findUser($token, null); } } if (!empty($request->query[$this->settings['parameter']])) { $token = $request->query[$this->settings['parameter']]; return $this->_findUser($token); } return false; } CakeFest 2012 Manchester
  • 59. REST my Cake Versioning /rest /v1 CakeFest 2012 Manchester
  • 60. REST my Cake THANKS CakeFest 2012 Manchester