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

Contenu connexe

Tendances

Js set timeout & setinterval
Js set timeout & setintervalJs set timeout & setinterval
Js set timeout & setinterval
ARIF MAHMUD RANA
 

Tendances (20)

Redux training
Redux trainingRedux training
Redux training
 
React Context API
React Context APIReact Context API
React Context API
 
CBSecurity 3 - Secure Your ColdBox Applications
CBSecurity 3 - Secure Your ColdBox ApplicationsCBSecurity 3 - Secure Your ColdBox Applications
CBSecurity 3 - Secure Your ColdBox Applications
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
Git을 조금 더 알아보자!
Git을 조금 더 알아보자!Git을 조금 더 알아보자!
Git을 조금 더 알아보자!
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 
[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?[143] Modern C++ 무조건 써야 해?
[143] Modern C++ 무조건 써야 해?
 
Js set timeout & setinterval
Js set timeout & setintervalJs set timeout & setinterval
Js set timeout & setinterval
 
Nodejs Explained with Examples
Nodejs Explained with ExamplesNodejs Explained with Examples
Nodejs Explained with Examples
 
Puppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node APIPuppeteer - Headless Chrome Node API
Puppeteer - Headless Chrome Node API
 
Structured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin CoroutinesStructured concurrency with Kotlin Coroutines
Structured concurrency with Kotlin Coroutines
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
Webpack Introduction
Webpack IntroductionWebpack Introduction
Webpack Introduction
 
An Intro into webpack
An Intro into webpackAn Intro into webpack
An Intro into webpack
 
Java script aula 07 - j-query
Java script   aula 07 - j-queryJava script   aula 07 - j-query
Java script aula 07 - j-query
 
파이썬 데이터베이스 연결 1탄
파이썬 데이터베이스 연결 1탄파이썬 데이터베이스 연결 1탄
파이썬 데이터베이스 연결 1탄
 
Rest API
Rest APIRest API
Rest API
 
[PHP 也有 Day #64] PHP 升級指南
[PHP 也有 Day #64] PHP 升級指南[PHP 也有 Day #64] PHP 升級指南
[PHP 也有 Day #64] PHP 升級指南
 
Fetch API Talk
Fetch API TalkFetch API Talk
Fetch API Talk
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 

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

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

Plus de Anuchit Chalothorn

Plus de 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
 

Dernier

Dernier (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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...
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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...
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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
 
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
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 

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) ));