SlideShare une entreprise Scribd logo
1  sur  60
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface pptTaha Malampatti
 
Codeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationCodeigniter : Two Step View - Concept Implementation
Codeigniter : Two Step View - Concept ImplementationAbdul Malik Ikhsan
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha 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 Symfony2Sumy PHP User Grpoup
 
An introduction to Laravel Passport
An introduction to Laravel PassportAn introduction to Laravel Passport
An introduction to Laravel PassportMichael Peacock
 
Using the new WordPress REST API
Using the new WordPress REST APIUsing the new WordPress REST API
Using the new WordPress REST APICaldera Labs
 
Hdfs connector
Hdfs connectorHdfs connector
Hdfs connectorkiranvanga
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSCarol McDonald
 
Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Migration from Rails2 to Rails3
Migration from Rails2 to Rails3Umair 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 Symfony2Sumy PHP User Grpoup
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSPGeethu Mohan
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgnitermirahman
 

Tendances (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
 

Similaire à 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 apiceeram
 
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
 
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 oneAdrian 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 FundamentalsIdo Flatow
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 
REST and Web API
REST and Web APIREST and Web API
REST and Web APIIT Weekend
 
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 AppGabriel Lucaciu
 
OData for iOS developers
OData for iOS developersOData for iOS developers
OData for iOS developersGlen Gordon
 
SharePoint 2013 REST APIs
SharePoint 2013 REST APIsSharePoint 2013 REST APIs
SharePoint 2013 REST APIsGiuseppe Marchi
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicehazzaz
 
Indic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhIndic threads delhi13-rest-anirudh
Indic threads delhi13-rest-anirudhAnirudh Bhatnagar
 

Similaire à 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
 

Dernier

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Dernier (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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