CakePHP PUT API with JSON Input

I am creating an API using CakePHP.

I want to use PUT from my mobile application to update data. The format is JSON as input, but $ this-> data seems to be null.

I am calling this url (as indicated in the docs) from my application: / recipes / 123.json

And in my β€œrecipes” (or something else) I have the following controller:

function edit($id = null) { $this->User->id = $id; if (empty($this->data)) { $this->data = $this->User->read(); $message = array('StatusCode' => 999, 'ERROR' => ""); } else { if ($this->User->save($this->data)) { $message = array('StatusCode' => 200, 'ErrorCode' => ""); } else { $message = array('StatusCode' => 400, 'ErrorCode' => "UnknownError"); } } $this->set(compact("message")); $this->set('albums', $this->User->Album->find('list')); } 

I get the JSON response correctly in my application, however I get error 999 - this means that the data $ this-> is empty. In my add function in my controller, where it receives JSON using POST, the $ this-> data is assigned correctly. And oh, if I use POST instead of PUT in my editing - the $ this-> data is set, but I can not save the data.

So how do I do this ?: S

+4
source share
2 answers

Insert from link luchomolina http://book.cakephp.org/2.0/en/controllers/request-response.html#accessing-xml-or-json-data

 //Get JSON encoded data submitted to a PUT/POST action $data = $this->request->input('json_decode'); 

and you will get your object.

 $data->Model->field ... 
+5
source

I have not tested it, but I think your data is in $this->request->input() or $this->request->data()

Additional Information:

http://book.cakephp.org/2.0/en/controllers/request-response.html#accessing-xml-or-json-data

http://book.cakephp.org/2.0/en/controllers/request-response.html#CakeRequest::data

0
source

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


All Articles