6

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

2 Answers 2

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

2 Comments

Yes but It will change only in in the api response but not change the http headers
@ArslanButt you may be experiencing some other problem. Those two are the same. The api response is over http, and it has one set of response headers and one response status code.
2

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.

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.