SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
REST API & CakePHP
Anuchit Chalothorn
anuchit@redlinesoft.net
Agenda
● REST
● Route
● Resource Mapping
REST
a style of software architecture for distributed
systems such as the WWW. The REST
language uses nouns and verbs, and has an
emphasis on readability. Unlike SOAP, REST
does not require a message header to and
from a service provider.
Concept
● the base URI for the web service, such as
http://example.com/resources/
● the Internet media type of the data
supported by the web service.
● the set of operations supported by the web
service using HTTP methods (e.g., GET,
PUT, POST, or DELETE).
● The API must be hypertext driven.
Example URI
● http://example.org/user/
● http://example.org/user/anuchit
● http://search.twitter.com/search.json?q=xxx
Example methods
Resource GET PUT POST DELETE
http://example.org/user list collection replace create delete
http://example.org/user/rose list data replace/ create ? / create delete
Simple Diagram
Requester Provider
GET /user/anuchit HTTP/1.1
200 with some data
No "official" standard
There is no "official" standard for RESTful web
services, This is because REST is an
architectural style, unlike SOAP, which is a
protocol.
Shortcut - Web Services design
● Choose method old style, new style
● Look around an eco-system
● Who'll using your services
● How to implementation
● Design and document
REST & CakePHP
The fastest way to get up and running with
REST is to add a few lines to your routes.php
file The Router object features a method called
mapResources(), that is used to set up a
number of default routes for REST access to
your controllers.
Route
If we wanted to allow REST access to a recipe
database, we’d do something like this:
//In app/Config/routes.php...
Router::mapResources('recipes');
Router::parseExtensions();
HTTP REQUEST Methods
HTTP Format URL.Format Controller action invoked
GET /recipes.format RecipesController::index()
POST /recipes.format RecipesController::add()
PUT /recipes/123.format RecipesController::edit(123)
DELETE /recipes/123.format RecipesController::delete(123)
POST /recipes/123.format RecipesController::edit(123)
REST & CakePHP
The fastest way to get up and running with
REST is to add a few lines to your routes.php
file The Router object features a method called
mapResources(), that is used to set up a
number of default routes for REST access to
your controllers.
Controller (1)
A basic controller might look something like this
// Controller/RecipesController.php
class RecipesController extends AppController {
public $components = array('RequestHandler');
public function index() {
$recipes = $this->Recipe->find('all');
$this->set(array(
'recipes' => $recipes,
'_serialize' => array('recipes')
));
}
Controller (2)
public function view($id) {
$recipe = $this->Recipe->findById($id);
$this->set(array(
'recipe' => $recipe,
'_serialize' => array('recipe')
));
}
Controller (3)
public function edit($id) {
$this->Recipe->id = $id;
if ($this->Recipe->save($this->request->data)) {
$message = 'Saved';
} else {
$message = 'Error';
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
Controller (4)
public function delete($id) {
if ($this->Recipe->delete($id)) {
$message = 'Deleted';
} else {
$message = 'Error';
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
View
Since we’ve added a call to Router::
parseExtensions(), the CakePHP router is
already primed to serve up different views
based on different kinds of requests.
Modify View (1)
If we wanted to modify the data before it is
converted into XML we should not define the
_serialize view variable and instead use view
files. We place the REST views for our
RecipesController inside app/View/recipes/xml.
Modify View (2)
// app/View/Recipes/xml/index.ctp
// Do some formatting and manipulation on
// the $recipes array.
$xml = Xml::fromArray(array('response' => $recipes));
echo $xml->asXML();
Resource Mapping
If the default REST routes don’t work for your
application, you can modify them using Router::
resourceMap().
Router::resourceMap(array(
array('action' => 'index', 'method' => 'GET', 'id' => false),
array('action' => 'view', 'method' => 'GET', 'id' => true),
array('action' => 'add', 'method' => 'POST', 'id' => false),
array('action' => 'edit', 'method' => 'PUT', 'id' => true),
array('action' => 'delete', 'method' => 'DELETE', 'id' => true),
array('action' => 'update', 'method' => 'POST', 'id' => true)
));
Thank You

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Visual programming lecture
Visual programming lecture Visual programming lecture
Visual programming lecture
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Lesson 5 php operators
Lesson 5   php operatorsLesson 5   php operators
Lesson 5 php operators
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Python intro
Python introPython intro
Python intro
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
Php
PhpPhp
Php
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Php Tutorials for Beginners
Php Tutorials for BeginnersPhp Tutorials for Beginners
Php Tutorials for Beginners
 
Java 9 Module System Introduction
Java 9 Module System IntroductionJava 9 Module System Introduction
Java 9 Module System Introduction
 
Bitbucket and Git
Bitbucket and GitBitbucket and Git
Bitbucket and Git
 
Laravel ppt
Laravel pptLaravel ppt
Laravel ppt
 
The Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReSTThe Internet as Web Services: introduction to ReST
The Internet as Web Services: introduction to ReST
 
Drupal Development
Drupal DevelopmentDrupal Development
Drupal Development
 
jQuery
jQueryjQuery
jQuery
 
Introducción a Foundation 5
Introducción a Foundation 5Introducción a Foundation 5
Introducción a Foundation 5
 
Laravel introduction
Laravel introductionLaravel introduction
Laravel introduction
 
Lesson 2 php data types
Lesson 2   php data typesLesson 2   php data types
Lesson 2 php data types
 
jQuery
jQueryjQuery
jQuery
 

Ähnlich wie REST API with CakePHP

nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
hazzaz
 
Services in Drupal 8
Services in Drupal 8Services in Drupal 8
Services in Drupal 8
Andrei Jechiu
 
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Nguyen Duc Phu
 
Designing Res Tful Rails Applications
Designing Res Tful Rails ApplicationsDesigning Res Tful Rails Applications
Designing Res Tful Rails Applications
ConSanFrancisco123
 

Ähnlich wie REST API with CakePHP (20)

Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest 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
 
REST principle & Playframework Routes
REST principle & Playframework RoutesREST principle & Playframework Routes
REST principle & Playframework Routes
 
RESTful Web Development with CakePHP
RESTful Web Development with CakePHPRESTful Web Development with CakePHP
RESTful Web Development with CakePHP
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
 
Rest And Rails
Rest And RailsRest And Rails
Rest And Rails
 
Services in Drupal 8
Services in Drupal 8Services in Drupal 8
Services in Drupal 8
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
 
Designing Res Tful Rails Applications
Designing Res Tful Rails ApplicationsDesigning Res Tful Rails Applications
Designing Res Tful Rails Applications
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Spring MVC 3 Restful
Spring MVC 3 RestfulSpring MVC 3 Restful
Spring MVC 3 Restful
 
Network Device Database Management with REST using Jersey
Network Device Database Management with REST using JerseyNetwork Device Database Management with REST using Jersey
Network Device Database Management with REST using Jersey
 
RESTful web services
RESTful web servicesRESTful web services
RESTful web services
 
Rest in Rails
Rest in RailsRest in Rails
Rest in Rails
 
Laravel
LaravelLaravel
Laravel
 
Day02 a pi.
Day02   a pi.Day02   a pi.
Day02 a pi.
 
Memphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basicsMemphis php 01 22-13 - laravel basics
Memphis php 01 22-13 - laravel basics
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 

Mehr von Anuchit Chalothorn

Mehr von Anuchit Chalothorn (20)

Flutter Workshop 2021 @ ARU
Flutter Workshop 2021 @ ARUFlutter Workshop 2021 @ ARU
Flutter Workshop 2021 @ ARU
 
Flutter workshop @ bang saen 2020
Flutter workshop @ bang saen 2020Flutter workshop @ bang saen 2020
Flutter workshop @ bang saen 2020
 
13 web service integration
13 web service integration13 web service integration
13 web service integration
 
09 material design
09 material design09 material design
09 material design
 
07 intent
07 intent07 intent
07 intent
 
05 binding and action
05 binding and action05 binding and action
05 binding and action
 
04 layout design and basic widget
04 layout design and basic widget04 layout design and basic widget
04 layout design and basic widget
 
03 activity life cycle
03 activity life cycle03 activity life cycle
03 activity life cycle
 
02 create your first app
02 create your first app02 create your first app
02 create your first app
 
01 introduction
01 introduction 01 introduction
01 introduction
 
Material Theme
Material ThemeMaterial Theme
Material Theme
 
00 Android Wear Setup Emulator
00 Android Wear Setup Emulator00 Android Wear Setup Emulator
00 Android Wear Setup Emulator
 
MongoDB Replication Cluster
MongoDB Replication ClusterMongoDB Replication Cluster
MongoDB Replication Cluster
 
MongoDB Shard Cluster
MongoDB Shard ClusterMongoDB Shard Cluster
MongoDB Shard Cluster
 
IT Automation with Chef
IT Automation with ChefIT Automation with Chef
IT Automation with Chef
 
IT Automation with Puppet Enterprise
IT Automation with Puppet EnterpriseIT Automation with Puppet Enterprise
IT Automation with Puppet Enterprise
 
Using PhoneGap Command Line
Using PhoneGap Command LineUsing PhoneGap Command Line
Using PhoneGap Command Line
 
Collaborative development with Git | Workshop
Collaborative development with Git | WorkshopCollaborative development with Git | Workshop
Collaborative development with Git | Workshop
 
OpenStack Cheat Sheet V2
OpenStack Cheat Sheet V2OpenStack Cheat Sheet V2
OpenStack Cheat Sheet V2
 
Open Stack Cheat Sheet V1
Open Stack Cheat Sheet V1Open Stack Cheat Sheet V1
Open Stack Cheat Sheet V1
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
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
Safe Software
 

Kürzlich hochgeladen (20)

ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
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
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
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
 
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
 
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, ...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 

REST API with CakePHP

  • 1. REST API & CakePHP Anuchit Chalothorn anuchit@redlinesoft.net
  • 2. Agenda ● REST ● Route ● Resource Mapping
  • 3. REST a style of software architecture for distributed systems such as the WWW. The REST language uses nouns and verbs, and has an emphasis on readability. Unlike SOAP, REST does not require a message header to and from a service provider.
  • 4. Concept ● the base URI for the web service, such as http://example.com/resources/ ● the Internet media type of the data supported by the web service. ● the set of operations supported by the web service using HTTP methods (e.g., GET, PUT, POST, or DELETE). ● The API must be hypertext driven.
  • 5. Example URI ● http://example.org/user/ ● http://example.org/user/anuchit ● http://search.twitter.com/search.json?q=xxx
  • 6. Example methods Resource GET PUT POST DELETE http://example.org/user list collection replace create delete http://example.org/user/rose list data replace/ create ? / create delete
  • 7. Simple Diagram Requester Provider GET /user/anuchit HTTP/1.1 200 with some data
  • 8. No "official" standard There is no "official" standard for RESTful web services, This is because REST is an architectural style, unlike SOAP, which is a protocol.
  • 9. Shortcut - Web Services design ● Choose method old style, new style ● Look around an eco-system ● Who'll using your services ● How to implementation ● Design and document
  • 10. REST & CakePHP The fastest way to get up and running with REST is to add a few lines to your routes.php file The Router object features a method called mapResources(), that is used to set up a number of default routes for REST access to your controllers.
  • 11. Route If we wanted to allow REST access to a recipe database, we’d do something like this: //In app/Config/routes.php... Router::mapResources('recipes'); Router::parseExtensions();
  • 12. HTTP REQUEST Methods HTTP Format URL.Format Controller action invoked GET /recipes.format RecipesController::index() POST /recipes.format RecipesController::add() PUT /recipes/123.format RecipesController::edit(123) DELETE /recipes/123.format RecipesController::delete(123) POST /recipes/123.format RecipesController::edit(123)
  • 13. REST & CakePHP The fastest way to get up and running with REST is to add a few lines to your routes.php file The Router object features a method called mapResources(), that is used to set up a number of default routes for REST access to your controllers.
  • 14. Controller (1) A basic controller might look something like this // Controller/RecipesController.php class RecipesController extends AppController { public $components = array('RequestHandler'); public function index() { $recipes = $this->Recipe->find('all'); $this->set(array( 'recipes' => $recipes, '_serialize' => array('recipes') )); }
  • 15. Controller (2) public function view($id) { $recipe = $this->Recipe->findById($id); $this->set(array( 'recipe' => $recipe, '_serialize' => array('recipe') )); }
  • 16. Controller (3) public function edit($id) { $this->Recipe->id = $id; if ($this->Recipe->save($this->request->data)) { $message = 'Saved'; } else { $message = 'Error'; } $this->set(array( 'message' => $message, '_serialize' => array('message') )); }
  • 17. Controller (4) public function delete($id) { if ($this->Recipe->delete($id)) { $message = 'Deleted'; } else { $message = 'Error'; } $this->set(array( 'message' => $message, '_serialize' => array('message') )); }
  • 18. View Since we’ve added a call to Router:: parseExtensions(), the CakePHP router is already primed to serve up different views based on different kinds of requests.
  • 19. Modify View (1) If we wanted to modify the data before it is converted into XML we should not define the _serialize view variable and instead use view files. We place the REST views for our RecipesController inside app/View/recipes/xml.
  • 20. Modify View (2) // app/View/Recipes/xml/index.ctp // Do some formatting and manipulation on // the $recipes array. $xml = Xml::fromArray(array('response' => $recipes)); echo $xml->asXML();
  • 21. Resource Mapping If the default REST routes don’t work for your application, you can modify them using Router:: resourceMap(). Router::resourceMap(array( array('action' => 'index', 'method' => 'GET', 'id' => false), array('action' => 'view', 'method' => 'GET', 'id' => true), array('action' => 'add', 'method' => 'POST', 'id' => false), array('action' => 'edit', 'method' => 'PUT', 'id' => true), array('action' => 'delete', 'method' => 'DELETE', 'id' => true), array('action' => 'update', 'method' => 'POST', 'id' => true) ));