Reputation: 660
I have the following in my configuration:
'modules' => [
'v0' => [
'class' => 'app\modules\v0\Module',
],
'v1' => [
'class' => 'app\modules\v1\Module',
],
],
And the following URL Manager entry:
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing'=>true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['v0/customer','v0/object']],
]
I have the following api calls for Update (PUT), View (GET), Delete (DELETE):
https://myapi.com/v0/objects/12345?name=warehouse
https://myapi.com/v0/objects/12345?name=product
I would like to be able for the user to access this using the following format: https://myapi.com/v0/objects/warehouse/12345
I have taken a look at rewrite rules but I think the module may be tricky. Can anyone shed some light on this for me please?
My web/.htaccess looks like this:
RewriteEngine on
# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php
Upvotes: 1
Views: 819
Reputation: 900
Try something like this... (not tested)
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v0/object',
'extraPatterns' => [
'GET <name:[\w-]+>/<id:\d+>' => 'view',
'PUT <name:[\w-]+>/<id:\d+>' => 'update',
'DELETE <name:[\w-]+>/<id:\d+>' => 'delete',
],
],
],
Assuming you have these methods in your ObjectController:
public function actionView($id, $name)
public function actionUpdate($id, $name)
public function actionDelete($id, $name)
Be careful if you extend ObjectController from yii\rest\controller as it defines defaults for update/view/delete/index (the questions doesn't tell). If so, I would rename the methods above and use the 'only' directive to only include these methods of the controller.
Upvotes: 0
Reputation: 660
SO after a bit of fiddling - this works. I think because I am using a module there are some things that get applied in the context of the module before the rules kick in. I think the rules are relative to the module/controller.
Anyhow - this works - I used patterns (as opposed to extraPatterns) because I want to explicitly define all the rules myself.
['class' => 'yii\rest\UrlRule', 'controller' => ['v0/object'], 'patterns'=>[
'GET <name>/<id>'=>'view',
'PUT <name>/<id>'=>'update',
'DELETE <name>/<id>'=>'delete',
'POST <name>'=>'create',
'GET <name>'=>'index',
]],
Upvotes: 1