Cald
Cald

Reputation: 781

CakePHP router cannot parse POST methods

I'm developing a CakePHP plugin which will be a Rest API kit and POST routes are not being parsed.

Routing

The problem is: Router::connect is not parsing any action with a different method than GET.

I would like to apply the common Rest routes like:

GET      /api/products       Get all products
GET      /api/products/:id   Get a single product
POST     /api/products       Create a product
PUT      /api/products/:id   Update a product
DELETE   /api/products/:id   Delete a product

I wouldn't like to use Router::mapResource to do that so I tried this:

// app/Config/core.php
Configure::write('Routing.prefixes', array('api')); 

// app/Config/bootstrap.php
CakePlugin::load('MY_PLUGIN', array('routes' => true));

// app/Config/routes.php
Router::parseExtensions('json');

// app/Plugin/MY_PLUGIN/Config/routes.php

Router::connect(
    '/api/:controller',
    array(
        'prefix' => 'api',
        'api' => true,
        'action' => 'index',
        'method' => 'GET',
    )
);

Router::connect(
    '/api/:controller/:id',
    array(
        'prefix' => 'api',
        'api' => true,
        'action' => 'view',
        'method' => 'GET',
    )
);

Router::connect(
    '/api/:controller',
    array(
        'prefix' => 'api',
        'api' => true,
        'action' => 'add',
        'method' => 'POST',
    )
);

I created a simple controller just to test it:

// app/Controller/ProductsController.php
public function api_index() {
    die('api_index');
}

public function api_view($id = null) {
    die('api_view');
}

public function api_add() {
    die('api_add');
}

Here's a list of responses that I get:

GET   /api/products      "api_index"
GET   /api/products/:id  "api_view"
POST  /api/products      "api_index"

Notice that the POST action couldn't find a proper route that match it. Anyone can explain it to me and knows a good solution for that?

Here's a list of questions that I already tried:

  1. CakePHP restful routes
  2. CakePHP REST route does not work

Upvotes: 1

Views: 1370

Answers (1)

D. Schalla
D. Schalla

Reputation: 655

As the Documentation on http://book.cakephp.org/2.0/en/development/routing.html#using-additional-conditions-when-matching-routes points out, you should use [method] and not method.

[method] Only match requests with specific HTTP verbs.

Router::connect(
'/api/:controller/*',
array(
    'prefix' => 'api',
    'api' => true,
    'action' => 'add',
    '[method]' => 'POST',
)
);

Upvotes: 2

Related Questions