JSON Response
JsonResponse
is the most feature-rich built-in response class in this package.
It is the right default for APIs because it combines three responsibilities:
- it behaves like a normal PSR-7 response;
- it sets the JSON
Content-Typeheader for you; - it keeps the original payload accessible through
getPayload().
Constructor Behavior
use FastForward\Http\Message\JsonResponse;
$response = new JsonResponse(
payload: ['status' => 'ok'],
charset: 'utf-8',
headers: ['X-App' => 'demo'],
);
By default, JsonResponse
:
- uses HTTP 200;
- sets
Content-Typetoapplication/json; charset=utf-8unless you choose another charset; - stores a JSON Stream instance as the body.
Reading the Payload Back
$response = new JsonResponse(['user' => 'Ada']);
$payload = $response->getPayload();
echo $payload['user']; // Ada
This is useful when a response object travels through more than one layer of your application.
Changing the Payload Immutably
$original = new JsonResponse(['step' => 1]);
$updated = $original->withPayload(['step' => 2]);
var_dump($original->getPayload()['step']); // 1
var_dump($updated->getPayload()['step']); // 2
The original instance is not modified.
Using Custom Status Codes
use FastForward\Http\Message\StatusCode;
$response = (new JsonResponse(['saved' => true]))
->withStatus(StatusCode::Created->value);
This keeps the convenience of JsonResponse
while still letting you control HTTP semantics.
When Not to Use It
Prefer another response type when:
- you want to send HTML to a browser: use HTML Response;
- you want to send plain text: use Text Response;
- you want no body at all: use Empty Response;
- you need only a reusable stream: use JSON Stream.
Common Gotcha
JsonResponse
relies on JSON encoding. If the payload contains a resource or invalid UTF-8 data,
encoding will fail. See Troubleshooting for recovery strategies.