REST

    While other solutions exist, REST is a great way to provide easy access to thelogic you’ve created in your application. It’s simple, usually XML-based (we’retalking simple XML, nothing like a SOAP envelope), and depends on HTTP headersfor direction. Exposing an API via REST in CakePHP is simple.

    The fastest way to get up and running with REST is to add a few lines to setupresource routes in your config/routes.php file.

    RESTful controllers often use parsed extensions to serve up different viewsbased on different kinds of requests. Since we’re dealing with REST requests,we’ll be making XML views. You can make JSON views using CakePHP’sbuilt-in . By using the built in we can define a _serialize view variable. This specialview variable is used to define which view variables XmlView shouldserialize into XML.

    If we wanted to modify the data before it is converted into XML we should notdefine the _serialize view variable, and instead use template files. We placethe REST views for our RecipesController inside src/Template/Recipes/xml. We can also usethe for quick-and-easy XML output in those views. Here’s whatour index view might look like:

    The rendered XML will end up looking something like this:

    Creating the logic for the edit action is a bit trickier, but not by much. Sinceyou’re providing an API that outputs XML, it’s a natural choice to receive XMLas input. Not to worry, theCake\Controller\Component\RequestHandler and classes make things much easier. If a POST orPUT request has an XML content-type, then the input is run through CakePHP’s class, and the array representation of the data is assigned to$this->request->getData(). Because of this feature, handling XML and POST data inparallel is seamless: no changes are required to the controller or model code.Everything you need should end up in $this->request->getData().

    CakePHP’s Router makes connecting RESTful resource routes easy. See the sectionon RESTful Routing for more information.