Yii 2.0 RESTful API Basic Configuration Tutorial
- 2021-11-10 09:09:52
- OfStack
Recently doing Yii 2.0 RESTful API function, looking for a long time of information, just find this kind of tutorial, thanks to the author, the following content according to my actual situation of the project to do 1 fixed modification.
Installing yii 2.0
After installing Composer, you can install the Yii application template by running the following command in a folder accessible to Web:
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
Initialize advanced templates
cd advanced
./init
The following appears when you enter "./init"
Yii Application Initialization Tool v1.0
Which environment do you want the application to be initialized in?
[0] Development
[1] ProductionYour choice [0-1, or "q" to quit] 0
Initialize the application under 'Development' environment? [yes|no] yes
Start initialization ...
Modify database connection properties
Open commonconfigmain-local. php to configure database connection information
'db' => [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=127.0.0.1;dbname=yii',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
],
Performing migrate database migration
./yii migrate
Copy the backend directory and name it api
Open apiconfigmain. php Modify id, controllerNamespace, etc. Replace all backend with api:
return [
'id' => 'app-api',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'api\controllers',
]
Open apiconfigmain. php Open url routing beautification rule
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
],
],
Open commonconfigbootstrap. php and add the following alias
Yii::setAlias('@api', dirname(dirname(__DIR__)) . '/api');
Why create an API application separately
The API application is created separately for easy maintenance and can avoid the following problems
Conflict of configuration Inconvenient naming of controller url beautification rule conflict The division of labor is clear, frontend is the foreground directory; backend is the background directory; api is the api directoryNext, open apicontrollers and create a new User controller, inherit yiirestActiveController and name it UserController, with the following code:
<?php
namespace api\controllers;
use yii\rest\ActiveController;
class UserController extends ActiveController
{
public $modelClass = 'common\models\User';
}
Configuring URL rules
Add url beautification rules to the user controller just now
Open apiconfigmain. php Modify the components property and add the following code:
...
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => 'user'
],
],
]
...
ok, which becomes an API conforming to RESTful style
It seems that nothing has been written in the controller, only a model has been specified, but many functions have been completed behind it. The list is as follows:
GET/users: List all users page by page HEAD/users: Display summary information for user list POST/users: Create a new user GET/users/123: Returns details for user 123 HEAD/users/123: Display overview information for user 123 PATCH/users/123: and PUT/users/123: Update User 123 DELETE/users/123: Deleting User 123 OPTIONS/users: Shows verbs about Terminal/users support OPTIONS/users/123: Shows verbs supported by Terminal/users/123
How to access it
You can access it using the curl command as follows:
curl -i -H "Accept:application/json" http://localhost/users
Command line is still more troublesome and inconvenient to test, recommended to use API testing tools
This kind of tool has a lot, I do not list 11, here recommended Postman, very good very powerful, Chorme also has plug-ins, can install, here I recommend direct download software installation debugging, more convenient
You may find access to any routing address is added s, users, why? Resources, you have to understand the word "resources". Since resources must be a collection, there must be a lot of resources, so you have to add plural numbers. I understand it this way.
You said I just don't want to add s, so I want to use http://localhost/user for access. OK, yes, I can satisfy you, but I don't recommend it.
Continue to open the configuration file apiconfigmain. php Modify the urlManager you just added as follows:
cd advanced
./init
0
Add 'pluralize' = > false, it means that the plural form is removed, and it is not recommended again
ok, we don't write any code in the controller, he generates many methods for us, but sometimes we may need to modify some code to achieve the desired effect, such as querying the table and then returning the data
Next, we will implement this function:
Open the newly created user controller and override the action method:
cd advanced
./init
1
So we can rewrite his code. Ha ha
Let's build another action of our own
cd advanced
./init
2
Then try to visit http://localhost/users/test and report an error? Can't find it?
It's right to report an error, because we didn't set up other routing access
Modification of apiconfigmain. php
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii\rest\UrlRule',
'controller' => 'user',
//'pluralize' => false, // Set to false You can get rid of the plural form
'extraPatterns'=>[
'GET send-email'=>'test'
],
],
],
]
There is no problem with reaccessing next, ps: Any action you write yourself must be configured on extraPatterns