Yii2 rest api does not return response code and status

I am trying to get (StatusCode) in response to a REST api, while its just the name of the returned field and an error message like this

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

I added an answer

 '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; } }, ], 
+5
source share
2 answers

Try this, it will work 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", ] ], ]; } 
+5
source
 Yii::$app->response->statusCode 

You can add this code to your action before returning your answer

0
source

All Articles