1

I am building a RESTful API with Yii2 (advanced) and endpoints are working as expected apart from a custom one I need.

My urlManagerlooks like:

        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => 
                ['class' => 'yii\rest\UrlRule', 'controller' => 'api/v1/step', 'pluralize' => false],
    ],

If I add a custom action into the StepController like so it will work just fine - Calling with http://example.com/api/v1/step/test

public function actionTest()

However if I want to pass an ID in through the path I will receive a 404 error - http://example.com/api/v1/step/test/1

public function actionTest($id)

Is there something I'm missing?

Edit: Adding notes that may help others.

My example above was simplified but what I wanted my URL to look like was like http://example.com/api/v1/step/test-by-foobar/1 with the called method to be public function actionTestByFoobar($id). However to get this to work you have to set the urlManager rule like the following which I didn't find obvious:

'api/v1/step/test-by-foobar/1' => 'api/v1/step/test-by-foobar',

Notice that the value is hyphenated, not in camel-case.

1 Answer 1

3

With your code you can pass an id like this :

http://example.com/api/v1/step/test?id=1

But if you want to do it like this:

http://example.com/api/v1/step/test/1

You should rewrite the url like below:

'urlManager' => [
     'enablePrettyUrl' => true,
     'showScriptName' => false,
     'rules' => [
            ['class' => 'yii\rest\UrlRule', 
             'controller' => 'api/v1/step', 
             'pluralize' => false
            ],

            /* You are missing this line below */
            'api/v1/step/test/<id:\d+>' => 'api/v1/step/test'
     ]
],
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I had tried that but obviously incorrectly. It's working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.