Why RESTfull API request to view return 404 in Yii

2019-07-29 00:52发布

问题:

I adjusted module api, and created controller UserController extends ActiveController. All work fine, but view return 404 error.

  • http://example.com/api/user/45 – return 404 (Error)
  • http://example.com/api/user/view/?id=45 - return 200 (Ok)

Why yii\rest\UrlRule don't work in this case?

Info from official page about this rule:

GET /users/123: return the details of the user 123;

ANSWER:

  1. Set yii\rest\UrlRule::$pluralize property to false;
  2. Set enableStrictParsing to false.

回答1:

1- Be sure to have the same configs as shown in related docs:

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    ],
]

2- Enabling Pretty Url in Yii requires further configurations at server level. For example if server is apache a similar configs to those should be added to htaccess file:

# Set document root to be "basic/web"
DocumentRoot "path/to/basic/web"

<Directory "path/to/basic/web">
    # use mod_rewrite for pretty URL support
    RewriteEngine on
    # If a directory or a file exists, use the request directly
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    # Otherwise forward the request to index.php
    RewriteRule . index.php

    # ...other settings...
</Directory>

More details and related configs to nginx can be found in the getting started section. Also check those tutorials for basic and advanced templates:

  • https://www.diggin-data.de/dd-cms/blog/post/view/id/1004/name/Creating+a+REST+API+for+Yii2-basic-template
  • http://budiirawan.com/setup-restful-api-yii2/

3- Depending on the project structure there is cases where you'll need to use RewriteBase or equivalent to define the base path holding your app. Like adding this to an apache's htaccess file:

RewriteBase /backend/api

4- From the rest quick start guide:

Yii will automatically pluralize controller names for use in endpoints. You can configure this using the yii\rest\UrlRule::$pluralize property.

Which means endpoint url is expected to look like http://example.com/api/users/45 by default.



标签: php rest yii yii2