CakePHP API PUT with JSON input

2019-05-07 12:00发布

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

2条回答
倾城 Initia
2楼-- · 2019-05-07 12:00

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 ...
查看更多
Fickle 薄情
3楼-- · 2019-05-07 12:07
登录 后发表回答