I am trying to use Yii 2 routing for REST API.
Following tutorial at http://www.yiiframework.com/doc-2.0/guide-rest-routing.html, I have already defined (with success) a lot of rule for API entry point like so :
'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        [
            'class' => 'yii\rest\UrlRule', 
            'controller' => 'user'
        ],
    ],
]
Such a rule defines :
Now, my users have games. So I'd like to have urls :
I tried defining my new entry point (withhout success) like so:
'rules' => [
    ... previous rules ...,
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => [
            'game'
        ],
        'tokens' => [
            '{userid}' => '<userid:\\d>',
            '{gameid}' => '<gameid:\\d>',
        ],
        'patterns' => [
            'GET,HEAD /users/{userid}/games' => 'index',
            'GET,HEAD /users/{userid}/games/{gameid}' => 'view',
        ]
    ]
]
This definition seems wrong because I get a 404 Page not found error. How should I define my new url routes ? I would like to use an equivalent format for my definitions, extending 'yii\rest\UrlRule'
I am not sure if this is even possible, the tutorial not mentionning this case.
So I figured out how to use more complex rules.
First, the solution, then the explanation.
Here is the solution:
'rules' => [
    ... previous rules ...,
    [
        'class' => 'yii\rest\UrlRule',
        'controller' => 'game',
        'prefix' => '/users/<userid:\\d+>',
        'tokens' => [
            '{gameid}' => '<gameid:\\d+>',
        ],
        'patterns' => [
            'GET,HEAD' => 'index',
            'GET,HEAD {gameid}' => 'view',
        ]
    ]
]
And now the explanation:
Do not forget the pluralization rule too ! "game" is singular" but valid urls will be
Hope it will help.
I think there´s a simple solutions, please try this:
'rules' => [
                ...
                '/users/<userId:\\d+>/games' => 'game/index' ,
                '/users/<userId:\\d+>/games/<gameId:\\d+>' => 'game/view' ,
                ....
];
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With