Changing status code of response with middleware #406
-
Hi, I'm dealing with an API that returns 200 even when the result array is empty and I'd like to change this to a 404. I have tried the method below and a few other variants, but I can't seem to get the status code to change that comes back after the middleware. (I have double checked and the middleware is definitely running.) I'm sure I'm missing something obvious! Many thanks in advance for your help! 🙂 class HasNoUsers implements ResponseMiddleware
{
public function __invoke(Response $response): Response
{
// If response body key 'users' is empty, set status code to 404
if (empty($response->body['users'])) {
$response->getPsrResponse()->withStatus(404);
}
return $response;
}
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Five minutes later I found a test in the source code and was able to see the pattern of how to reincorporate a new response. I'm sure I had looked before! 😆 Answer if anyone has the same issue! public function __invoke(Response $response): Response
{
if (empty($response->body['users'])) {
$psrResponse = $response->getPsrResponse();
$newPsrResponse = $psrResponse->withStatus(404);
return $response::fromPsrResponse($newPsrResponse, $response->getPendingRequest(), $response->getPsrRequest());
}
return $response;
} |
Beta Was this translation helpful? Give feedback.
Five minutes later I found a test in the source code and was able to see the pattern of how to reincorporate a new response. I'm sure I had looked before! 😆
Answer if anyone has the same issue!