Pluralized and non-pluralized rules for the same REST controller

The quickest way of adding REST support to your Yii 2 application is to add REST controller to it and configure REST rules. Just a couple of line and framework will do all the dirty stuff for you “behind the scene”.

If you do this then your REST rules will have pluralize property set to true be default meaning that even though you are using controller’s name in singular (i.e. UserController, PostController etc.) your REST URL rules will have it in plural, i.e. GET /posts/12, DELETE /posts/13 etc.

Since I am a purification and perfection maniac, I wasn’t pretty much satisfied with the idea that:

  • I have plural routes when fetching, deleting or updating single record (when pluralize = true) or
  • I have single GET /post router when fetching all records (when pluralize = false)

In other words, I wanted a solution that will give me:

  • Everything in singular (i.e. GET /post/12, PATCH /post/77)
  • Except listing all the records, where I will have plural (i.e. GET /posts)

The solution turned out to be quite simple…

…however it required using of two separate yii\rest\UrlRule instances for single model:

[
    'class' => 'yii\rest\UrlRule',
    'controller' => 'user',
    'pluralize' => false,
    'except' => ['index'],
],
[
    'class' => 'yii\rest\UrlRule',
    'controller' => 'user',
    'patterns' => [
        'GET,HEAD' => 'index',
        '' => 'options',
    ],
],

First instance defines all singular routes, so except index action. Second instance is a specific instance to only define index action (for listing all records) in plural form.

When you use the above configuration then singular form will work for any route operating on single record, i.e.:

And the plural form will work for listing of all records:

If you try to list all records using singular form then you’ll hit the wall with…

HTTP Error 405 Method Not Allowed, which is perfectly fine, since this method… is not allowed.

Leave a Reply