Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Restful API - Example to Add a New Action

Tags:

rest

api

yii2

For buiding restful API using Yii2, does anyone has good example on how to add a new action in a controller? Thanks.

like image 420
Qinjie Avatar asked Sep 06 '14 14:09

Qinjie


People also ask

What is controller in Yii2?

CController manages a set of actions which deal with the corresponding user requests. Through the actions, CController coordinates the data flow between models and views.


2 Answers

I am not sure if you are asking for extra actions beside CRUD or just for CRUD, so I write in details for both cases.

Firstly, the framework includes \yii\rest\ActiveController that provides typical restful API operation and URL management.

Basically, the controller predefines the CRUD operations as followed:

POST /resource -> actionCreate -> Create the resource

GET /resource/{id} -> actionView -> Read the resource

PUT, PATCH /resource/{id} -> actionUpdate -> Update the resource

DELETE /resource/{id} -> actionDelete -> Delete the resource

GET /resource -> actionIndex -> List all the resources

The URL routing rules and actions definition can be found in \yii\rest\ActiveController, \yii\rest\UrlRule and the respective \yii\rest\*Action.

Secondly, if you want to add extra restful API in the controller, you can simply write your extra actionXxxxx(), and in configuration, add the following url rules under urlManager:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        [
            'class' => 'yii\rest\UrlRule',
            'controller' => ['resource'],
            'pluralize' => false,
            'extraPatterns' => [
                'POST {id}/your_preferred_url' => 'xxxxx', // 'xxxxx' refers to 'actionXxxxx'
            ],
        ],
    ],
],

Effectively, this will generate a new routing rule, requesting POST /resource/{id}/your_preferred_url will invoke actionXxxxx of your ResourceController.

like image 191
Victor Wong Avatar answered Sep 21 '22 01:09

Victor Wong


Here is a good example using Yii 2 advanced application template

https://github.com/deerawan/yii2-advanced-api

more detail of this project http://budiirawan.com/setup-restful-api-yii2/

also you can use Yii 2 basic application template if you want. what you have to do is follow this kind of folder structure (v1 for version) (Yii doc -A module may consist of sub-modules.)(GiovanniDerks - backend sub-modules)

-modules
--api
---v1
----controllers
----models
like image 29
Chanuka Asanka Avatar answered Sep 25 '22 01:09

Chanuka Asanka