Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Rest URL Routing

Tags:

rest

php

yii

yii2

I have a problem calling the url of my rest api in Yii2. I want to call a url like:

http://localhost/index-dev.php/myapi/collection/18

where 18 is the Id.

In my web.php config, I have the following code, with other settings from another programmers :

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => true,
        'rules' => [
            ['class' => 'yii\rest\UrlRule', 'controller' => ['coding/nodes', 'coding/scales','myapi/collection']],                
            '<controller:\w+>/<id:\d+>' => '<controller>/view',
        ],            
    ],

when i call my URL, i get

Not Found (#404)

What am i doing wrong?

like image 632
Wael Avatar asked Dec 14 '22 14:12

Wael


2 Answers

I had the same problem, you can disable the prural

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => true,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => ['coding/nodes', 'coding/scales','myapi/collection']],                
        '<controller:\w+>/<id:\d+>' => '<controller>/view',
        'pluralize' => false,
    ],            
],
like image 71
Hugo Avatar answered Dec 17 '22 03:12

Hugo


You need to use the plural of your model class name in the URL for accessing a single model:

http://localhost/index-dev.php/myapi/collections/18

Take a look at the documentation of yii\rest\UrlRule:

The above code will create a whole set of URL rules supporting the following RESTful API endpoints:

  • 'PUT,PATCH users/<id>' => 'user/update': update a user
  • 'DELETE users/<id>' => 'user/delete': delete a user
  • 'GET,HEAD users/<id>' => 'user/view': return the details/overview/options of a user
  • 'POST users' => 'user/create': create a new user
  • 'GET,HEAD users' => 'user/index': return a list/overview/options of users
  • 'users/<id>' => 'user/options': process all unhandled verbs of a user
  • 'users' => 'user/options': process all unhandled verbs of user collection
like image 32
vim Avatar answered Dec 17 '22 03:12

vim