LoginSignup
3
4

More than 1 year has passed since last update.

CakePHP3でjsonを返すAPIのHTTP status codeを設定したい人生だった

Last updated at Posted at 2018-06-15

CakePHP3でjsonを返すAPIをCakePHPの流儀に従って記述量少なく書きたい人生だったの続き。

REST APIを書いていると、jsonとともにHTTP status codeを設定したいことがある。

だめな方法

$this->response->statusCode(403);
@deprecated 3.4.0 Use `getStatusCode()` and `withStatus()` instead.

動くけどだめです。
ずっと今のバージョンを使うならこれで良いだろう。

なるほど withStatus

$this->response->withStatus(400);

200が返る…。
withStatusの戻りをreturnすると今度はbodyが返らない。

結局こうした

$response = new Response();
$response = $response->withType('application/json')
  ->withStatus($status)
  ->withStringBody(json_encode($something));
return $response;

動いたけど、本当にこれしかないの?
json_encodeとか書きたくないし、前回と比べて統一感がなさすぎる。

3
4
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4