Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change status code in http header in yii2 RESTful api

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

like image 423
Arslan Butt Avatar asked Apr 16 '17 11:04

Arslan Butt


2 Answers

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;
like image 142
Jørgen Avatar answered Sep 23 '22 09:09

Jørgen


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.

like image 20
111 Avatar answered Sep 24 '22 09:09

111