CakePHP API PUT with JSON input

2019-05-07 12:13发布

问题:

I am building 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 call this url (as specified in the docs) from my application: /recipes/123.json

And in my "recipes" (or whatever) 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 correctly receive the JSON response in my application however I get the 999 error - meaning that $this->data is empty. In my add function in my controller where it receives JSON using POST - the $this->data gets assigned correctly. And oh ye, if I use POST instead of PUT in my edit - the $this->data gets set, but I cannot save the data..

So.. how do I do this ? :S

回答1:

Insert from luchomolina's link 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 get your object.

$data->Model->field ...


回答2:

I haven't tested it, but I think your data is in $this->request->input() or $this->request->data()

More info:

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