Yii2 Rest URL 路由

Yii2 Rest URL Routing

我在 Yii2 中调用其余 api 的 url 时遇到问题。我想给 url 打电话:

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

其中 18 是 ID。

在我的 web.php 配置中,我有以下代码,以及来自其他程序员的其他设置:

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

当我调用 URL 时,我得到

未找到 (#404)

我做错了什么?

您需要在 URL 中使用模型 class 名称的复数形式才能访问单个模型:

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

看看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

我遇到了同样的问题,你可以关闭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,
    ],            
],

我建议为 API 创建单独的模块 并像这样配置你的 UrlManager...:)

'urlManager' => [
            'enablePrettyUrl' => true,
            'enableStrictParsing' => true,
            'showScriptName' => false,
            'rules' => [
                [
                    'class' => 'yii\rest\UrlRule', 
                    'pluralize'=>false,
                    'controller' => ['v1/country','v1/user'],
                    'tokens' => [
                        '{id}' => '<id:\w+>'
                    ],
                    'extraPatterns' => [
                        'POST register' => 'register', //from url 
                        'GET exists'=>'exists',
                        'POST login'=>'login',
                        'POST follow'=>'follow',
                        'POST category'=>'category',
                        'PUT profile'=>'profile',
                        'PUT change_password'=>'change_password',
                        'PUT feed_interested'=>'feed_interested',
                    ],


                ]
            ],        
        ]

更多详情@Create Rest Api