When building an API, it’s too easy to think about the right way for things to work and you often fail to think about all the mistakes people can make when learning to use the right API. The Rest API format that was in use for Cake 1.x versions and Cake 2.x versions are completely different. And the Rest api code of cake 1.x won’t work in cake 2.x.
Even you follow the book format to code, there are high level chances of coder getting the error Xml parser or Xml declaration not ended properly.
Here is an out of box or out of book way to code API, which works very similar to Rest API. And best part of this type is that it is ‘Coder Friendly’ and error free.
I’m listing out the steps to be followed to create API

Step 1 : Allow access to the method without login. i.e, auth allow
Ex : $this->Auth->allow(‘your function name’); in before filter function.
Step 2 : Create a layout file in Views/Layouts. Let it have only the following content
Step 3 : Auhorize the model that you use for authentication. If you need to load the model, then load it after authorizing the model.
Ex : $this->Auth->authorize = array(‘model’=>’Model name used for authentication’);
$this->loadModel(‘Model name used for authentication’);
Now, your function is ready for authentication against the data provided.
Step 4 : Business logic. After authentication you can put all your business logic that needs to be executed similar to the way that you
code in application.
Step 5 : Process the data so that the result to be passed is in the array format.
Step 6 : Convert array to xml, because only xml format can be passed back as the result to Http requests that are made.
Please note : Array cannot be passed as the reult to http requests.
Function to convert array to xml is given below :
public function array2xml($array, $xml = false){
if($xml === false){
$xml = new SimpleXMLElement(”);
foreach($array as $key => $value){
$this->array2xml($value, $xml->addChild($key));
$xml->addChild($key, $value);
return $xml->asXML();
Step 7 : Set the data to view as you do in normal application.
Example : $this->set(compact(‘variable’));
Do not forget to add this line after setting the variable to view $this->set(‘_serialize’, array(‘variable’));
Step 8 : Create a normal view file with functionname.ctp in view/table_name folder. With the following content
Your function is now ready to accept any http request, the data posted through http requests mentioned in book.cakephp.org are obtained in $this->data. And xml format result will be the output of the request.

Contact Us On WhatsApp