@lew
Here are the steps to create a RESTful API in Yii:
- Install Yii using composer:
1
|
composer create-project yiisoft/yii2-app-basic api
|
- Configure the web application by editing the web.php file. Add the following configuration for URL routing:
1
2
3
4
5
6
7
8
|
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
['class' => 'yii
estUrlRule', 'controller' => 'api'],
],
],
|
- Create a new controller by running the following command in the console:
1
|
php yii gii/controller --controllerClass=apiController --enableI18N=0 --enableWebAccess=1
|
- Add actions to the controller for each API endpoint:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
class ApiController extends yii
estController
{
public function actionIndex()
{
return [
'message' => 'Welcome to the API.',
];
}
public function actionUsers()
{
$users = [
['id' => 1, 'name' => 'John Doe'],
['id' => 2, 'name' => 'Jane Smith'],
];
return $users;
}
public function actionUser($id)
{
$user = [
'id' => $id,
'name' => 'John Doe',
];
return $user;
}
}
|
- Access the API endpoints by making HTTP requests to the appropriate URLs:
1
2
|
http://localhost/api/users
http://localhost/api/user/1
|
That's it! You've created a RESTful API in Yii.