CakePHP - creating an API for my cakephp application

I have created a fully functional CakePHP web application. Now I want to go to the next level and make my application more "open". So I want to create a RESTful API. In the CakePHP docs, I found this link ( http://book.cakephp.org/2.0/en/development/rest.html ) that describes a way to make your application RESTful. I added two lines to route.php as needed, as indicated at the top of the link, and now I want to test it. I have a UserController.php controller where there is an add () function that adds new users to the databases. But when I try to browse under mydomain.com/users.json (even with HTTP POST), this returns me a web page, not a json formatted page, as I expected.

Now I think I did something wrong or I did not understand something correctly. What is really going on, can you help me a little?

Thank you at advace!

+4
source share
1 answer

You need to parse the JSON extensions. So in the routes.php file add:

Router::parseExtensions('json'); 

So, a URL like http://example.com/news/index , now you can access like http://example.com/news/index.json .

To actually return JSON, you need to change the controller methods. You need to set the _serialize key in your action so that your news controller can look like this:

 <?php class NewsController extends AppController { public function index() { $news = $this->paginate('News'); $this->set('news', $news); $this->set('_serialize', array('news')); } } 

Here are the basics. For POST requests, you want to use the RequestHandler component. Add it to the controller:

 <?php class NewsController extends AppController { public $components = array( 'RequestHandler', ... ); 

And then you can check if the incoming request used the .json extension:

 public function add() { if ($this->RequestHandler->extension == 'json') { // JSON request } else { // do things as normal } } 
+9
source

Source: https://habr.com/ru/post/1497790/


All Articles