0
votes

I'm trying to create a RESTful api with CakePHP that will add a user when a POST request is sent to /users.json. After the user is created, the client will be redirected to the page with the JSON representation of the user. The code I have for the controller is:

class UsersController extends AppController {

    public $components = array('RequestHandler');

    public function view($id) {
        $user = $this->User->findById($id);
        $this->set(array(
            'user' => $user['User'],
            '_serialize' => 'user'
        ));
    }

    public function add() {
        if ($this->User->save($this->data)) {
            $this->redirect(array('action' => 'view', 1)); //using 1 just to test
        } else {
            print_r($this->User->validationErrors);
            $this->set(array(
            'errors' => $this->User->validationErrors,
            '_serialize' => array('errors')
        ));
        }
    }
}

I have added Router::mapResources('users') and Router::parseExtensions('json') to routes.php. However, when I send a post request using Chrome's REST console plugin, I get a response of "{errors:[]}" and no new user is created. When I use curl, a user is created but I don't get a json representation of the user after. Any idea what's going on?

1
Can you also use a tool like Fiddler to see what's going on in the requests underneath? - mellamokb
Ok I didn't pass the proper parameters before. Now I'm getting "The view for UsersController::view() was not found". I believe this is because the redirect is going to /users/1 rather than /users/1.json. - shoopdelang
I would not recommend redirecting in REST calls, just override redirect() in your controller to just render the same action in case you get a json request - José Lorenzo Rodríguez
I'm just following cake's documentation for REST. What do you mean by "render the same action in case you get a json request"? - shoopdelang

1 Answers

0
votes

If you have not already done, then retry after creating app/View/user/json/index.ctp With following content:

<?php
return json_encode(compact());
?>