Skip to content

Responses

Every route handler ends by producing a response. In a Nimbus application you rarely build one by hand: return an array and you get JSON, return a string and you get text, return a resource and you get a consistent data envelope. When you need full control, the same Pam\Http\Response object that the runtime uses is injected into your handler.

The simplest handlers return a value:

routes.php
$router->get('/greeting', fn () => 'Hello World');
$router->get('/status', fn () => ['status' => 'ok', 'version' => '1.4.0']);
Terminal window
$ curl -i http://127.0.0.1:3000/greeting
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
Hello World
$ curl http://127.0.0.1:3000/status
{"status":"ok","version":"1.4.0"}

Arrays and JsonSerializable objects become JSON with application/json; charset=utf-8. Strings and numbers become a text/plain body.

Type-hint Pam\Http\Response to set the status code, headers and body yourself. Every method returns the response, so calls chain:

routes.php
use Pam\Http\Request;
use Pam\Http\Response;
$router->post('/products', fn (Request $request, Response $response) => $response
->status(201)
->header('location', '/api/products/3')
->json(['id' => 3], 201));
Terminal window
$ curl -i -X POST http://127.0.0.1:3000/products
HTTP/1.1 201 Created
location: /api/products/3
content-type: application/json; charset=utf-8
{"id":3}
Method Description
status(int $code) Sets the status code.
header(string $name, string $value) Sets a header, replacing earlier values.
addHeader(string $name, string $value) Adds another value for a header.
send($body) Sets the body (string, number, boolean, or null for none).
json(mixed $data, int $status = 200) Sends JSON with the given status.
cookie(string $name, string $value = '', array $options = []) Adds a Set-Cookie header.
stream(), streamOutput(), sse() Stream the body; see Streaming.

If a handler returns an array but a middleware or the handler already set a status on the injected response, that status is kept:

use Pam\Http\Response;
$router->post('/jobs', function (Response $response): array {
$response->status(202);
return ['queued' => true]; // 202 Accepted
});

Send null with a 204 status. No content-type is added for 204 and 304 responses:

$router->delete('/sessions/current', fn (Request $request, Response $response) => $response
->status(204)
->send(null));

Nimbus encodes JSON with JSON_UNESCAPED_UNICODE, so café stays café instead of café. Forward slashes are escaped:

Terminal window
$ curl http://127.0.0.1:3000/arr
{"name":"café","url":"https:\/\/example.com\/a"}

An application that replaces a Laravel service and must send the same bytes can switch every JSON response Nimbus writes to Laravel’s encoding once, at boot:

bootstrap/app.php
use Nimbus\Http\JsonEncoding;
$app->jsonEncoding(JsonEncoding::LARAVEL);

To write JSON with a custom status, flags or content type from anywhere, use JsonEncoding::respond():

use Nimbus\Http\JsonEncoding;
return JsonEncoding::respond($response, ['ok' => true], 200, contentType: 'application/vnd.acme+json');

Resources turn your domain objects into the JSON your API promises, in one place. Generate one with the CLI:

Terminal window
pam make:resource ProductResource
app/Resources/ProductResource.php
<?php
declare(strict_types=1);
namespace App\Resources;
use Nimbus\Http\JsonResource;
use Pam\Http\Request;
final readonly class ProductResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->resource['id'],
'name' => $this->resource['name'],
'price' => $this->resource['price'] / 100,
];
}
}

$this->resource is whatever you passed to the constructor: an array, an entity, any value. Return the resource from a handler; the second constructor argument is the status code:

public function show(string $id): ProductResource
{
return new ProductResource($this->products->find((int) $id));
}
public function store(StoreProductRequest $request): ProductResource
{
return new ProductResource($this->products->create($request->validated()), 201);
}
Terminal window
$ curl http://127.0.0.1:3000/api/products/2
{"data":{"id":2,"name":"Mouse","price":19}}

collection() wraps a list of items. The response is a data array, plus meta and links when you pass a paginated Nimbus\Pagination\Page:

public function index(): ResourceCollection
{
return ProductResource::collection($this->products->all());
}
Terminal window
$ curl http://127.0.0.1:3000/api/products
{"data":[{"id":1,"name":"Keyboard","price":49},{"id":2,"name":"Mouse","price":19}]}

Add your own metadata with withMeta():

return ProductResource::collection($products)->withMeta(['total' => count($products)]);

Return a Nimbus\Http\Redirect. The default status is 302; any 3xx status is accepted:

use Nimbus\Http\Redirect;
$router->get('/home', fn () => Redirect::to('/dashboard'));
$router->get('/old-pricing', fn () => Redirect::to('/pricing', 301));

Redirect::back($request, '/') sends the user to the Referer when it belongs to the same host, and to the fallback otherwise, so it cannot be abused as an open redirect.

Attach a cookie to any response with cookie(). The supported options are expires, max-age, domain, path, samesite, secure and httponly:

$router->post('/prefs', fn (Request $request, Response $response) => $response
->cookie('theme', 'dark', [
'max-age' => 60 * 60 * 24 * 365,
'path' => '/',
'secure' => true,
'httponly' => true,
'samesite' => 'Lax',
])
->json(['ok' => true]));
set-cookie: theme=dark; Max-Age=31536000; Path=/; Secure; HttpOnly; SameSite=Lax

To delete a cookie, send it again with 'max-age' => 0.

For signed-in browser applications, register EncryptCookiesMiddleware and queue cookies on the injected Nimbus\Http\CookieJar (make(), queue(), forget()); they are encrypted with APP_KEY and written when the response leaves.

Stream a file from disk instead of loading it into memory. Set content-disposition to make the browser save it:

routes.php
$router->get('/reports/{id}/download', function (string $id, Response $response): Response {
$stream = fopen("/var/lib/acme/reports/{$id}.csv", 'rb')
?: throw new \Nimbus\Http\HttpException(404, \Nimbus\Http\ProblemCode::NotFound, 'Report not found.');
return $response
->header('content-disposition', 'attachment; filename="report.csv"')
->stream((function () use ($stream): Generator {
try {
while (!feof($stream)) {
yield fread($stream, 64 * 1024);
}
} finally {
fclose($stream);
}
})(), 'text/csv');
})->where('id', \Nimbus\RouteConstraint::Integer);

The finally block closes the file even when the client disconnects halfway through.

stream() sends each chunk of an iterable as soon as it is produced; sse() formats Server-Sent Events; streamOutput() captures echo output. All three use chunked transfer encoding and apply backpressure: a slow client suspends the request Fiber instead of filling memory.

$router->get('/events', fn (Request $request, Response $response) => $response->sse([
['tick' => 1],
['tick' => 2],
]));
data: {"tick":1}
data: {"tick":2}

See Streams & SSE for long-lived streams, and HTTP Server for the size limits that apply.

Every GET route also answers HEAD. Nimbus runs the handler and all middleware, then removes the body, so headers such as content-type and custom headers are identical to the GET response.