Arslan Butt
Arslan Butt

Reputation: 795

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

Upvotes: 6

Views: 9134

Answers (2)

111
111

Reputation: 1918

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.

Upvotes: 2

Jørgen
Jørgen

Reputation: 3567

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;

Upvotes: 12

Related Questions