Q:

How to change keys lable of yii2 advanced API response

I have created API module in my yii2 advanced application and also added HttpBearerAuth in controller file and it is working.
On Unauthorized I'm getting below response : 
{"name":"Unauthorized","message":"Your request was made with invalid credentials.","code":0,"status":401,"type":"yii\\web\\UnauthorizedHttpException"}

I want to change key label of this response like below : 
{"error":"Unauthorized","errorMessage":"Your request was made with invalid credentials.","code":0,"status":401}

How do I update these keys?

A:

Attach an event handler to yii\web\Response::EVENT_BEFORE_SEND and examine the $data attribute of the yii\web\Response class. Not sure, but guess you'll find an array where the keys are exactly those that you want to change.
You just need to filter out the responses you want to handle (eg everything except status codes 200 & 201).
Maybe something like this... probably bugs included :-)
Event::on(yii\web\Response::className(), yii\web\Response::EVENT_BEFORE_SEND, function ($event) {
    if (Yii::$app->response->getStatusCode() > 201) {
        if (isset(Yii::$app->response->data['name']) {
            Yii::$app->response->data['error'] = Yii::$app->response->data['name'];
            unset(Yii::$app->response->data['name']);
        }
    }
});

