Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 rest api is not returning response code and status

I am trying to get (StatusCode) in response of REST api while its just return field name and error message like this

[{"field":"Email","message":"Email \"[email protected]\" has already been taken."}]

I have added response

'response' => [
        'class' => 'yii\web\Response',
        'on beforeSend' => function ($event) {
            $response = $event->sender;
            if ($response->data !== null && Yii::$app->request->get('suppress_response_code')) {
                $response->data = [
                    'success' => $response->isSuccessful,
                    'data' => $response->data,
                ];
                $response->statusCode = 200;
            }
        },

    ],
like image 773
naCheex Avatar asked Aug 11 '15 07:08

naCheex


1 Answers

Try that way, it works for me:

if ("some error checking goes there") {
    Yii::$app->response->statusCode = 422;//I preferred that error code
    return [
        "data" => [
            'errors' => [
                'fieldname' => "Field Name is invalid",
            ]
        ],
    ];
}
like image 79
Bandydan Avatar answered Sep 23 '22 23:09

Bandydan