To have your app restfully is a good way to increase your app audience. REST is an XML-based method to allow access to your app using HTTP headers. It is light, simple, and have well-organized formats that organize even a very complex application.

CakePHP and Rest

CakePHP framework allows you to make your restful api in an easy way by two main steps:

Step1 :  Configure resource routing

In ‘config/routes.php’ , We will add these lines to allow REST access to TopicsController.

After setting up REST routes you can access your controller actions using URLs like this: http://yourdomain/Topics/index.json ,http://yourdomain/Topics/view/2.json .The URL has a suffix of the REST format ‘json’ or ‘xml’.Or you will get an error message says that CakePHP misses controller’s method.

Step 2 : Serialize Output

If you have your Controller basic CRUD, you can modify it to serialize its output. So, Controller responses will be in JSON or XML format depending on the routes.

TopicsController.php will be like that

You can see that weused_serialize variable to specify the variable that will be serialized into xml or json.

Accessing API

Try the index and view actions in your browser using next URLs as they use GET HTTP method.





add, edit, and delete actions uses POST HTTP method. So, If you don’t have an app capable of testing Header’s Request.

You might use

REST Client plugin for Firefox

Postman Plugin for Chrome

Cocoa REST Client for Mac.

I am using postman plugin with chrome.

In delete action, I queried http://localhost/topics/delete/26.json using POST HTTP method and this was the response.

In add action, I queried http://localhost/topics/add.json using POST HTTP method .And sent a user data with the request.
This was the json response.

In this tutorial, you learned the basics of using REST in CakePHP.
If you have any questions feel free to write your comment.