I am using Yii2
for restful api and its working fine. However I want to change status in header. Suppose I want to access users ID 13 record and this id not found in database so my api response will be
{"name":"Not Found","message":"","code":0,"status":404}
but in header status
is 200
I need same status in header as in api response that is 404
if record not found. How I can change the header status according to api response
Yii::$app->response->statusCode = 404;
Source: http://www.yiiframework.com/doc-2.0/guide-runtime-responses.html
The guide also suggest to throw errors to change the status codes.
throw new \yii\web\NotFoundHttpException;
I would use the controller to throw a 404 instead of setting the response code. You can add this in your controller action after finding the model.
if ( !$model) {
throw new HttpException(404, Yii::t('app','Record not found.'));
}
This will work with a JSON API or regular HTML.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With