5

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;
            }
        },

    ],
4
  • so you only set the statuscode if suppress_response_code is sent via $_GET? Commented Aug 11, 2015 at 7:58
  • But I am not getting status response in any case.... Commented Aug 11, 2015 at 9:26
  • 2
    @AliRaza try to remove the second part Yii::$app->request->get('suppress_response_code') and test it. If it fails then $response->data is null. Commented Aug 11, 2015 at 9:45
  • setting controller response as "return $model;" instead of "return $model->errors;" will automatically set appropriate status code. Commented Jan 19, 2017 at 10:51

2 Answers 2

5

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",
            ]
        ],
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

0
Yii::$app->response->statusCode

You can Add in you action this code, before return your response

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.