yii2yii2-api

Custom action in Action with id in Rest ActiveController Yii2


Trying to implement a GET method in Rest API, to query the user status e.g. GET user/:id/status

So getting the status of user id #1 would call /user/1/status

In config I have:

'urlManager'   => [
'enablePrettyUrl'     => true,
'enableStrictParsing' => true,
'showScriptName'      => false,
'rules'               => [
    [
        'class'      => 'yii\rest\UrlRule',
        'controller' => [
            'v1/user'
        ],
        'extraPatterns' => [
            'GET status' => 'status',
        ],
        'tokens'     => [
            '{id}' => '<id:\\w+>'
        ],
    ],
],

User Model:

namespace api\modules\v1\models;

use \yii\db\ActiveRecord;

class User extends ActiveRecord {
    /**
     * @inheritdoc
     */
    public static function tableName() {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey() {
        return [ 'id' ];
    }

}

User Controller:

namespace api\modules\v1\controllers;

use yii\rest\ActiveController;

class UserController extends ActiveController {

    public $modelClass = 'api\modules\v1\models\User';

    public function actions() {
        $actions = parent::actions();

        unset(
            $actions[ 'index' ],
            $actions[ 'view' ],
            $actions[ 'create' ],
            $actions[ 'update' ],
            $actions[ 'delete' ],
            $actions[ 'options' ]
        );


        return $actions;
    }

    protected function verbs() {
        return [
            'status' => [ 'GET' ],
        ];
    }

    public function actionStatus( $id ) {

        return 1;
    }

}

But now I'm not sure on how to actually return the data for the call.


Solution

  • $user = User::findOne($id);
    if ($user)
        return Json::encode(['success'=>true, 'data'=>$user->status]);
    else
        return Json::encode(['success'=>false, 'message'=>"Can't find user"]);