What is REST?
REST (Representational State Transfer) is a style of
software architecture mainly used for web services to
communicate between servers and clients using
existing features of the HTTP protocol.
The main HTTP verbs/methods used in REST are GET,
POST, PUT and DELETE
Most companies online who offer APIs and webservices use REST.
Who’s using REST?
Why use REST?
You’ve already wrote the code! Use your existing code
with little changes.
Open your application to the public. Allow other
developers to integrate your application into their projects
or extend the functionality of your application.
Create applications on multiple platforms. Using your
REST API you can build mobile and desktop applications
using your existing code base.
REST in CakePHP
REST in CakePHP is simple.
Add RESTful controllers to Router::mapResources() to set up
default routes in /config/router.php.
Add desired extensions to Router::parseExtension() eg. xml,
json, yaml, etc. in /config/router.php.
Add RequestHandler component to controllers with REST
CakePHP RESTful routing
HTTP Method URL Controller Action
GET /recipes.ext RecipesController::index()
GET /recipes/123.ext RecipesController::view(123)
POST /recipes.ext RecipesController::add()
PUT /recipes/123.ext RecipesController::edit(123)
DELETE /recipes/123.ext RecipesController::delete(123)
POST /recipes/123.ext RecipesController::edit(123)
Custom RESTful routing
If you have additional methods in your controller that don’t
correspond to the default CRUD functionality you can add
additional routes for those methods.
array("action" => ”custom_action", "[method]" => "PUT"),
array("id" => "[0-9]+")
Specifying HTTP methods
CakePHP's Router class uses a number of different indicators to detect the
HTTP method being used. Here they are in order of preference:
The _method POST variable
The REQUEST_METHOD header
The _method POST variable is helpful in using a browser as a REST client (or
anything else that can do POST easily). Just set the value of _method to
the name of the HTTP request method you wish to emulate.
Setting up views for
additional content types
CakePHP knows when using Router::parseExtensions() to look for content
types in a child directory named after the content type.
If we want to create an index action for our recipe controller with a content
type of json we would create the following file:
Don’t forget to create a default layout for the content type as well.
Consuming RESTful APIs
CakePHP’s build in HttpSocket class works great for
consuming RESTful APIs and it’s easy to use!
Neil Crookes released an Oauth extension to Cake’s built
CakePHP REST Plugin
Kevin van Zonneveld (kvz) has released and
maintains a REST plugin that features
authentication, rate-limiting per IP, automatic
generation of xml and json views and support for
Visit my blog http://andrw.net and follow me on twitter